package com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.casualtiesDE.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzfxqh.base.dict.service.DictItemService;
import com.css.fxfzfxqh.base.dict.service.DictService;
import com.css.fxfzfxqh.base.dict.viewobjects.DictEntityVo;
import com.css.fxfzfxqh.common.rest.JcsjRestManager;
import com.css.fxfzfxqh.common.rest.model.param.JcsjDataViewParam;
import com.css.fxfzfxqh.common.rest.model.vo.JcsjDataViewVo;
import com.css.fxfzfxqh.constants.FxfzConstants;
import com.css.fxfzfxqh.constants.YNEnum;
import com.css.fxfzfxqh.modules.buildingIndividual.entity.BuildingIndividualEntity;
import com.css.fxfzfxqh.modules.buildingIndividual.repository.BuildingIndividualRepository;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.exceptions.BizException;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.exceptions.StrategyFactoryException;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.model.param.QueryByVersionParam;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.repository.FxqhBuildingGridVersionRepository;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.service.FxqhBuildingGridDataVersionService;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.service.FxqhBuildingGridService;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.strategy.StrategyFactory;
import com.css.fxfzfxqh.modules.buildings.calculationTasks.entity.CalculationTasks;
import com.css.fxfzfxqh.modules.buildings.calculationTasks.repository.CalculationTasksRepository;
import com.css.fxfzfxqh.modules.buildings.calculationTasks.service.CalculationTasksService;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.casualtiesDE.entity.*;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.casualtiesDE.param.CasualtiesDECalculationParam;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.casualtiesDE.param.SysDataVersionPageParam;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.casualtiesDE.repository.CasualtiesDERepository;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.casualtiesDE.service.CasualtiesDEService1;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.casualtiesDE.vo.*;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.economicLossDE.repository.EconomicLossEDRepository;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.resistEarthquakesDE.entity.PCCName;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.resistEarthquakesDE.param.AssessParam;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.resistEarthquakesDE.service.impl.ResistEarthquakesDEServiceImpl;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.resistEarthquakesDE.vo.JcLd;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.resistEarthquakesDE.vo.JcPga;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.resistEarthquakesDE.vo.ResistEarthquakesPCCVO;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.util.YSXUtil;
import com.css.fxfzfxqh.modules.population.service.PopulationService;
import com.css.fxfzfxqh.modules.seismicHazardData.entity.SettingInfluenceFliedEntity;
import com.css.fxfzfxqh.modules.seismicHazardData.repository.SeismicImpactFieldRepository;
import com.css.fxfzfxqh.modules.singleIndexRiskZoning.model.entity.FxqhAssessEdQh;
import com.css.fxfzfxqh.modules.singleIndexRiskZoning.model.entity.FxqhAssessEdQhResult;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.util.YSXEntity;
import com.css.fxfzfxqh.modules.synthesis.vo.QhSynthesisExportVO;
import com.css.fxfzfxqh.modules.util.ExcelUtil;
import com.css.fxfzfxqh.modules.util.hypergraph.service.HypergraphService;
import com.css.fxfzfxqh.modules.util.repository.PccRepository;
import com.css.fxfzfxqh.modules.util.repository.YSXRepository;
import com.css.fxfzfxqh.util.*;
import com.css.fxfzfxqh.web.PlatformSessionContext;
import com.css.fxfzfxqh.zcpt.sys.entity.SUser;
import com.css.fxfzfxqh.zcpt.sys.service.SUserService;
import com.css.fxfzfxqh.zcpt.sys.service.SysAreaService;
import com.google.common.base.Functions;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFDataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author: zhangSongRui
 * @CreateTime: 2023/06/08
 * @Description: 人员伤亡确定评估
 */
@Slf4j
@Service
public class CasualtiesDEServiceImpl1 implements CasualtiesDEService1 {
    @Resource
    private EconomicLossEDRepository economicLossEDRepository;
    @Resource
    private CasualtiesDERepository casualtiesDERepository;
    @Resource
    private SysAreaService sysAreaService;
    @Resource
    DictService dictService;
    @Resource
    SUserService sUserService;
    @Resource
    PccRepository pccRepository;
    @Autowired
    JcsjRestManager jcsjRestManager;
    @Autowired
    private FxqhBuildingGridService fxqhBuildingGridService;
    @Resource
    private YSXUtil ySXUtil;
    @Resource
    private FxqhBuildingGridDataVersionService fxqhBuildingGridDataVersionService;
    @Resource
    FxqhBuildingGridVersionRepository fxqhBuildingGridVersionRepository;
    @Resource
    private HypergraphService hypergraphService;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private StrategyFactory strategyFactory;
    @Autowired
    DictItemService dictItemService;
    @Resource
    PopulationService populationService;
    @Resource
    BuildingIndividualRepository buildingIndividualRepository;
    @Resource
    SeismicImpactFieldRepository seismicImpactFieldRepository;
    @Resource
    CalculationTasksService calculationTasksService;
    @Resource
    CalculationTasksRepository calculationTasksRepository;

    private static final String CASUALTIES_SS = "rysw1"; // 受伤
    private static final String CASUALTIES_SW = "rysw2"; // 死亡
    private static final String PHCD = "pgcd5"; // 默认破坏程度，倒塌
    private static final String[] GRID_TABLE_ARR = {
            "fxqh_building_grid_rural_bottom_frame",
            "fxqh_building_grid_rural_civil",
            "fxqh_building_grid_rural_masonry",
            "fxqh_building_grid_rural_mixed",
            "fxqh_building_grid_rural_other",
            "fxqh_building_grid_rural_steel",
            "fxqh_building_grid_rural_steel_concrete",
            "fxqh_building_grid_rural_wood_bamboo",
            "fxqh_building_grid_urban_masonry",
            "fxqh_building_grid_urban_other",
            "fxqh_building_grid_urban_steel",
            "fxqh_building_grid_urban_steel_concrete",
            "fxqh_building_grid_urban_wood",
    };

    private ThreadLocal<Integer> dlIdIndex = ThreadLocal.withInitial(() -> 1);

    @Override
    @Transactional(rollbackFor=Exception.class)
    public void addAssess(CasualtiesDE param) throws Exception {
        String user = sUserService.getSUser(PlatformSessionContext.getUserID());
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        param.setId(UUIDGenerator.getUUID());
        param.setCreateUser(sUser.getCreateUser());
        param.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        param.setDelFlag(YNEnum.N.toString());
        //创建人单位
        param.setCompany(sUser.getOrgName());
        param.setCreateUserName(sUser.getUserName());
        //写入省市县
        if ("0".equals(param.getRadio2())) {
            setCCP(param);
        } else if ("2".equals(param.getRadio2())) {
            String areaRange = param.getAreaRange();
            areaRange = areaRange.replace("；", ";").replace("，", ",");
            //检查输入的范围的头一个经纬度和最后一个经纬度是否相同
            check(areaRange);
            String geomText = isGeomValid(areaRange);
            param.setGeom(geomText);
            param.setCoordinateRange(geomText);
        }
        casualtiesDERepository.addAssess(param);
    }

    //输入的经纬度范围是否自相交
    public String isGeomValid(String areaRange) throws Exception {
        String newAreaRange = areaRange.replace(",", " ");
        newAreaRange = newAreaRange.replace(";", ",");
        String geomText = "POLYGON((" + newAreaRange + "))";
        try {
            String result = casualtiesDERepository.isGeomValid(geomText);
            if ("f".equals(result)) {
                throw new RuntimeException("保存失败，输入的经纬度自相交");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("保存失败，输入的经纬度范围异常");
        }
        return geomText;
    }

    //输入的经纬度范围是否在中国范围内切收尾经纬度是否相同
    public void check(String areaRange) throws Exception {
        //校验准确性
        String[] split = areaRange.split(";");
        for (String range : split) {
            String longitude = range.split(",")[0];
            String latitude = range.split(",")[1];
            if (new BigDecimal(longitude).compareTo(new BigDecimal(73)) < 0 || new BigDecimal(longitude).compareTo(new BigDecimal(136)) > 0) {
                throw new RuntimeException("保存失败," + longitude + "不在中国范围内");
            }
            if (new BigDecimal(latitude).compareTo(new BigDecimal(0)) < 0 || new BigDecimal(latitude).compareTo(new BigDecimal(54)) > 0) {
                throw new RuntimeException("保存失败," + latitude + "不在中国范围内");
            }
        }
        //检查第一个经纬度是否和最后一个经纬度相同（必须相同）
        String first = split[0];
        //头一个经度
        String firstLongitude = first.split(",")[0];
        //头一个纬度
        String firstLatitude = first.split(",")[1];
        String end = split[split.length - 1];
        //头一个经度
        String lastLongitude = end.split(",")[0];
        //头一个纬度
        String lastLatitude = end.split(",")[1];
        if (!firstLongitude.equals(lastLongitude) && !firstLatitude.equals(lastLatitude)) {
            throw new RuntimeException("保存失败,输入经纬度范围的第一个经纬度和最后一个经纬度不相同");
        }

    }

    //写入省市县
    private void setCCP(CasualtiesDE param) {
        List<PCC> pccList1 = new ArrayList<>();
        List<PCC> pccList = param.getList();
        if (pccList.size() != 0) {
            for (PCC pcc : pccList) {
                if (PlatformObjectUtils.isNotEmpty(pcc.getPpName())) {
                    if (PlatformObjectUtils.isEmpty(pcc.getCityName())) {
                        String childArea1 = sysAreaService.getChildAreaById(pcc.getPid());
                        List<PCCName> objects1 = JSON.parseArray(childArea1, PCCName.class);
                        for (PCCName pccName1 : objects1) {
                            String childArea2 = sysAreaService.getChildAreaById(pccName1.getId());
                            List<PCCName> objects2 = JSON.parseArray(childArea2, PCCName.class);
                            for (PCCName pccName2 : objects2) {
                                PCC pcc1 = new PCC();
                                pcc1.setAssessId(param.getId());
                                pcc1.setUuid(UUIDGenerator.getUUID());
                                pcc1.setPid(pcc.getPid());
                                pcc1.setPpName(pcc.getPpName());
                                pcc1.setCid(pccName1.getId());
                                pcc1.setCityName(pccName1.getName());
                                pcc1.setName(pccName2.getName());
                                pcc1.setId(pccName2.getId());
                                pccList1.add(pcc1);
                            }
                        }
                    } else {
                        if (PlatformObjectUtils.isEmpty(pcc.getName())) {
                            String childArea = sysAreaService.getChildAreaById(pcc.getCid());
                            List<PCCName> objects = JSON.parseArray(childArea, PCCName.class);
                            for (PCCName pccName : objects) {
                                PCC pcc1 = new PCC();
                                pcc1.setAssessId(param.getId());
                                pcc1.setUuid(UUIDGenerator.getUUID());
                                pcc1.setPid(pcc.getPid());
                                pcc1.setPpName(pcc.getPpName());
                                pcc1.setCid(pcc.getCid());
                                pcc1.setCityName(pcc.getCityName());
                                pcc1.setName(pccName.getName());
                                pcc1.setId(pccName.getId());
                                pccList1.add(pcc1);
                            }
                        } else {
                            pcc.setAssessId(param.getId());
                            pcc.setUuid(UUIDGenerator.getUUID());
                            pccList1.add(pcc);
                        }
                    }
                } else {
                    pcc.setAssessId(param.getId());
                    pcc.setUuid(UUIDGenerator.getUUID());
                    pccList1.add(pcc);
                }
            }
            pccRepository.batchSavePCC(pccList1);
        }
    }

    //查询评估记录
    @Override
    public EvaluateViewVO findById(String id) {
        EvaluateViewVO vo = new EvaluateViewVO();
        CasualtiesDE byId = casualtiesDERepository.findById(id);
        List<PCC> list = pccRepository.queryToponym(byId.getId());
        byId.setList(list);
        vo.setCasualtiesde(byId);
        //默认展示地震输入方式为烈度的下6度的白天死亡人数信息
        String condition = "";
        if ("0".equals(byId.getSeismicInputMode())) {
            condition = "ld1";
        } else if ("1".equals(byId.getSeismicInputMode())) {
            condition = "sgglsz1";
        }
//        else if("2".equals(byId.getSeismicInputMode())){
//            condition = "";
//        }
        Map<String, Object> map = this.queryCalculation(1, 20, byId.getSeismicInputMode(), id, condition, "rysw1", "sjd1");
        vo.setMap(map);
        return vo;
    }

    private CasualtiesDE getById(String id) {
        CalculationTasks task = calculationTasksRepository.findById(id);
        CasualtiesDE byId = new CasualtiesDE();
        BeanUtils.copyProperties(task,byId);
        List<PCC> list = pccRepository.queryToponym(id);
        byId.setList(list);
        return byId;
    }

    //修改评估记录
    @Override
    @Transactional(rollbackFor=Exception.class)
    public void upDateAssess(CasualtiesDE param) {
        param.setUpdateUser(PlatformSessionContext.getUserID());
        param.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        casualtiesDERepository.upDateAssess(param);
    }

    //获取评估记录code
    @Override
    public String getCode(CasualtiesDE param) {
        //抗震能力确定评估
        StringBuilder code = new StringBuilder("JZW-RY-QD");
        if (param.getHouseDataFlag().equals("0")) {
            //单体
            code.append("-DT");
        } else if (param.getHouseDataFlag().equals("1")) {
            //网格
            code.append("-WG");
        }
        if (StringUtils.isEmpty(param.getCoordinateRange())) {
            //如果经纬度范围为空
            code.append("-QH");
        } else {
            code.append("-QD");
        }
        if (param.getSeismicInputMode().equals("0")) {
            //烈度
            code.append("-LD");
        } else if (param.getSeismicInputMode().equals("1")) {
            //概率水准
            code.append("-GL");
        } else if (param.getSeismicInputMode().equals("2")) {
            //地震影响场
            code.append("-YX");
        }
        String[] split1 = code.toString().split("-");
        if (split1.length != 6) {
            return code.toString();
        }
        //查询最近一次code
        String oldCode = casualtiesDERepository.queryLatest(code);
        if (StringUtils.isEmpty(oldCode)) {
            code.append("-0001");
        } else {
            String[] split = oldCode.split("-");
            code.append("-").append(getNext(split[6]));
        }
        return code.toString();
    }

    //分页
    @Override
    public Map<String, Object> getPage(int curPage, int pageSize, AssessParam param) {
        Map<String, Object> page = casualtiesDERepository.getPage(curPage, pageSize, param);
        List<CasualtiesDE> list = (List<CasualtiesDE>) page.get("rows");
        for (CasualtiesDE obj : list) {
            List<PCC> pccs = pccRepository.queryToponym(obj.getId());
            obj.setList(pccs);
        }
        page.put("rows", list);
        return page;
    }

    //计算
//    @Override
//    @SneakyThrows
//    public void calculation1(CasualtiesDECalculation param) {
//        CasualtiesDE byId = findById(param.getAssessId());
//        //初始时间
//        long startTime = System.currentTimeMillis();
//        //如果为网格数据
//        if (byId.getHouseDataFlag().equals("1")) {
//            //写入分页查询条件
//            FxqhBuildingGridDataVersionPageParam fxqhBuildingGridDataVersionPageParam = new FxqhBuildingGridDataVersionPageParam();
//            //数据视图条件
//            QueryByVersionParam queryByVersionParam = new QueryByVersionParam();
//            //因为县最多的四川省也就一百多个县,乘上13个结构类型也就2000多,所以这里直接分页查询五千条
//            fxqhBuildingGridDataVersionPageParam.setPage(1);
//            fxqhBuildingGridDataVersionPageParam.setRows(5000);
//            //根据省市县获取易损性值 TODO 临时提出来
//            HashMap<String, Map<String, Map<String, YSX>>> ysxData = null;
//            //获得所有评估县
//            List<PCC> pccList = byId.getList();
//            for (PCC pcc : pccList) {
//                //第一步根据省市县获取公里网格版本号
//                //写入省id
//                fxqhBuildingGridDataVersionPageParam.setDataRangeProvince(pcc.getPid());
//                //写入市id
//                fxqhBuildingGridDataVersionPageParam.setDataRangeCity(pcc.getCid());
//                //写入县id
////                fxqhBuildingGridDataVersionPageParam.setDataRangeArea(pcc.getId());
//                //根据写入条件查询对应的公里网格数据
//                PageResult<FxqhBuildingGridDataVersionPageVo> page = fxqhBuildingGridDataVersionService.page(fxqhBuildingGridDataVersionPageParam);
//
//                //第二步根据取出的13个公里网格版本号获取具体的公里网格数据
//                //取出公里网格版本,给个县下应该有13个房屋结构类型也可能更少
//                List<FxqhBuildingGridDataVersionPageVo> pageData = page.getList();
//                //十三个结构类型的值的list;计算用
//                List<Calculation> calculationList = new ArrayList<>();
//                //根据省市县获取易损性值
//                if (ysxData == null) {
//                    ysxData = getYSX(pcc.getPpName(), pcc.getCityName(), "");
//                }
//                //获取当前烈度和破获程度
//                //破坏程度
//                String damageDegree = dictService.getValueByDictCodeAndKey("pgcd", PHCD);
//                //烈度
//                String condition = param.getCondition();
//
//                //循环获得的13个房屋结构类型的计算值
//                for (FxqhBuildingGridDataVersionPageVo pageDatum : pageData) {
//                    //写入条件版本号
//                    queryByVersionParam.setVersionCode(pageDatum.getVersionCode());
//                    //获取房屋结构类型的字典值
//                    String type = dictService.getKeyByDictCodeAndValue("jzwglgwlx", pageDatum.getDataType());
//                    //根据字典值获取不同结构类型的具体数据
//                    try {
//                        calculationList.addAll(getTypeValue(type, condition, damageDegree, ysxData, queryByVersionParam));
//                    } catch (StrategyFactoryException e) {
//                        e.printStackTrace();
//                    } catch (BizException e) {
//                        e.printStackTrace();
//                    }
//                }
//                //计算最终结果并入库
//                List<CasualtiesDECalculation> conditionValue = getConditionValue(param, byId, calculationList, pcc);
//                System.out.println("开始入库");
//                if (conditionValue.size() != 0) {
//                    casualtiesDERepository.batchCalculation(conditionValue);
//                }
//                System.out.println("入库结束");
//                //结束时间
//                long endTime = System.currentTimeMillis();
//                System.out.println("程序运行时间：" + (endTime - startTime) + "ms");
//            }
//        }
//        //刷新指定超图工作空间数据源数据集
//        boolean bool = hypergraphService.getWorkspaceReload("fxqh_resist_earthquakes_calculation_ed");
//        if (bool){
//            log.info("刷新成功");
//        }else {
//            log.info("刷新失败");
//        }
//    }

    private List<BuildingVulnerability> getBuildingVulnerabilityList(List<YSXEntity> v1, String k1) {
        List<BuildingVulnerability> vulnerabilityList = new ArrayList<>();
        BuildingVulnerability buildingVulnerability = new BuildingVulnerability();
        Double baisc = v1.get(0).getIntensity6();
        Double slight = v1.get(1).getIntensity6();
        Double mid = v1.get(2).getIntensity6();
        Double serious = v1.get(3).getIntensity6();
        Double destory = v1.get(4).getIntensity6();

        buildingVulnerability.setBasic(baisc == null ? BigDecimal.ZERO : BigDecimal.valueOf(baisc));
        buildingVulnerability.setSlight(slight == null ? BigDecimal.ZERO : BigDecimal.valueOf(slight));
        buildingVulnerability.setMid(mid == null ? BigDecimal.ZERO : BigDecimal.valueOf(mid));
        buildingVulnerability.setSerious(serious == null ? BigDecimal.ZERO : BigDecimal.valueOf(serious));
        buildingVulnerability.setDestroy(destory == null ? BigDecimal.ZERO : BigDecimal.valueOf(destory));
        buildingVulnerability.setSfIntensity(k1);
        buildingVulnerability.setIntensity("6");
        vulnerabilityList.add(buildingVulnerability);
        buildingVulnerability = new BuildingVulnerability();
        baisc = v1.get(0).getIntensity7();
        slight = v1.get(1).getIntensity7();
        mid = v1.get(2).getIntensity7();
        serious = v1.get(3).getIntensity7();
        destory = v1.get(4).getIntensity7();
        buildingVulnerability.setBasic(baisc == null ? BigDecimal.ZERO : BigDecimal.valueOf(baisc));
        buildingVulnerability.setSlight(slight == null ? BigDecimal.ZERO : BigDecimal.valueOf(slight));
        buildingVulnerability.setMid(mid == null ? BigDecimal.ZERO : BigDecimal.valueOf(mid));
        buildingVulnerability.setSerious(serious == null ? BigDecimal.ZERO : BigDecimal.valueOf(serious));
        buildingVulnerability.setDestroy(destory == null ? BigDecimal.ZERO : BigDecimal.valueOf(destory));
        buildingVulnerability.setSfIntensity(k1);
        buildingVulnerability.setIntensity("7");
        vulnerabilityList.add(buildingVulnerability);
        buildingVulnerability = new BuildingVulnerability();
        baisc = v1.get(0).getIntensity8();
        slight = v1.get(1).getIntensity8();
        mid = v1.get(2).getIntensity8();
        serious = v1.get(3).getIntensity8();
        destory = v1.get(4).getIntensity8();
        buildingVulnerability.setBasic(baisc == null ? BigDecimal.ZERO : BigDecimal.valueOf(baisc));
        buildingVulnerability.setSlight(slight == null ? BigDecimal.ZERO : BigDecimal.valueOf(slight));
        buildingVulnerability.setMid(mid == null ? BigDecimal.ZERO : BigDecimal.valueOf(mid));
        buildingVulnerability.setSerious(serious == null ? BigDecimal.ZERO : BigDecimal.valueOf(serious));
        buildingVulnerability.setDestroy(destory == null ? BigDecimal.ZERO : BigDecimal.valueOf(destory));
        buildingVulnerability.setSfIntensity(k1);
        buildingVulnerability.setIntensity("8");
        vulnerabilityList.add(buildingVulnerability);
        buildingVulnerability = new BuildingVulnerability();
        baisc = v1.get(0).getIntensity9();
        slight = v1.get(1).getIntensity9();
        mid = v1.get(2).getIntensity9();
        serious = v1.get(3).getIntensity9();
        destory = v1.get(4).getIntensity9();
        buildingVulnerability.setBasic(baisc == null ? BigDecimal.ZERO : BigDecimal.valueOf(baisc));
        buildingVulnerability.setSlight(slight == null ? BigDecimal.ZERO : BigDecimal.valueOf(slight));
        buildingVulnerability.setMid(mid == null ? BigDecimal.ZERO : BigDecimal.valueOf(mid));
        buildingVulnerability.setSerious(serious == null ? BigDecimal.ZERO : BigDecimal.valueOf(serious));
        buildingVulnerability.setDestroy(destory == null ? BigDecimal.ZERO : BigDecimal.valueOf(destory));
        buildingVulnerability.setSfIntensity(k1);
        buildingVulnerability.setIntensity("9");
        vulnerabilityList.add(buildingVulnerability);
        buildingVulnerability = new BuildingVulnerability();
        baisc = v1.get(0).getIntensity10();
        slight = v1.get(1).getIntensity10();
        mid = v1.get(2).getIntensity10();
        serious = v1.get(3).getIntensity10();
        destory = v1.get(4).getIntensity10();
        buildingVulnerability.setBasic(baisc == null ? BigDecimal.ZERO : BigDecimal.valueOf(baisc));
        buildingVulnerability.setSlight(slight == null ? BigDecimal.ZERO : BigDecimal.valueOf(slight));
        buildingVulnerability.setMid(mid == null ? BigDecimal.ZERO : BigDecimal.valueOf(mid));
        buildingVulnerability.setSerious(serious == null ? BigDecimal.ZERO : BigDecimal.valueOf(serious));
        buildingVulnerability.setDestroy(destory == null ? BigDecimal.ZERO : BigDecimal.valueOf(destory));
        buildingVulnerability.setSfIntensity(k1);
        buildingVulnerability.setIntensity("10");
        vulnerabilityList.add(buildingVulnerability);
        return vulnerabilityList;
    }

    private List<LinkedHashMap> getPopoluationList(String populationVersion, PCC pcc) throws BizException {
        JcsjDataViewParam jcsjDataViewParam = new JcsjDataViewParam();
        jcsjDataViewParam.setVersionCode(populationVersion);
        if (pcc != null) {
            jcsjDataViewParam.setProvince(pcc.getPpName());
            jcsjDataViewParam.setCity(pcc.getCityName());
            jcsjDataViewParam.setCounty(pcc.getName());
        }
        JcsjDataViewVo data = populationService.queryDataView(jcsjDataViewParam).getData();
        if (data == null || PlatformObjectUtils.isEmpty(data.getData())) {
            return null;
        }
        return (List<LinkedHashMap>) data.getData();
    }

    // //根据省市县查询易损性并处理结果
    // private Table<String, String, List<BuildingVulnerability>> handleYsxData(PCC pcc) throws Exception {
    //     //查询县的易损性数据
    //     List<YSXEntity> ysxEntityList = ysxRepository.getYSX(pcc.getPpName(), pcc.getCityName(), pcc.getName());
    //     if (ysxEntityList == null || ysxEntityList.size() == 0) {
    //         throw new RuntimeException("评估失败,请维护" + pcc.getPpName() + "-" + pcc.getCityName() + "-" + pcc.getName() + "的易损性数据");
    //     }
    //     Table<String, String, Map<String, BuildingVulnerability>> ysxTable = HashBasedTable.create();
    //     // BiMap sfIntensityMap = BiMap
    //     if (PlatformObjectUtils.isNotEmpty(ysxEntityList)) {
    //         //collect的key是建筑物结构类型   value是相同结构类型的集合
    //         Map<String, List<YSXEntity>> collect = ysxEntityList.stream().collect(Collectors.groupingBy(YSXEntity::getStructure_type));
    //         collect.forEach((k, v) -> {
    //             Map<String, List<YSXEntity>> fortifyMap = v.stream().collect(Collectors.groupingBy(YSXEntity::getFortify));
    //             //k1是设防烈度
    //             fortifyMap.forEach((k1, v1) -> {
    //                 List<BuildingVulnerability> vulnerabilityList = getBuildingVulnerabilityList(v1, k1);
    //                 ysxTable.put(k, k1, vulnerabilityList);
    //             });
    //         });
    //     }
    //     return ysxTable;
    // }
    //
    private QueryByVersionParam createGridSelectCondition(String version, PCC pcc) {
        //数据视图条件
        QueryByVersionParam queryByVersionParam = new QueryByVersionParam();
        //写入条件版本号
        queryByVersionParam.setVersionCode(version);
        queryByVersionParam.setProvince(pcc.getPpName());
        queryByVersionParam.setCity(pcc.getCityName());
        queryByVersionParam.setCounty(pcc.getName());
        return queryByVersionParam;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void calculation(String assessId, String seismicInputMode) throws Exception {
        //先删除这个评估记录之前生成的结果
        casualtiesDERepository.deleteEvaluateResult(assessId, seismicInputMode);
        // CasualtiesDE casualtiesDE = this.getById(assessId);
        CalculationTasks calculationTasks = calculationTasksService.findById(assessId);
        String type = calculationTasks.getLdPga();
        String version = calculationTasks.getInfluenceFieldVersion();
        //现在新建任务的时候如果不选就是空， 如果选了没计算就是0 ；计算完成是1；
        if ("0".equals(seismicInputMode)) {
            if (PlatformObjectUtils.isNotEmpty(calculationTasks.getStructuralLdProgress()) && "0".equals(calculationTasks.getStructuralLdProgress())) {
                throw new RuntimeException("请先计算结构破坏-烈度的确认评估！");
            }
        } else if ("2".equals(seismicInputMode)) {
            if (PlatformObjectUtils.isNotEmpty(calculationTasks.getStructuralFieldProgress()) && "0".equals(calculationTasks.getStructuralFieldProgress())) {
                throw new RuntimeException("请先计算结构破坏-地震影响场的确认评估！");
            }
        } else if ("1".equals(seismicInputMode)) {
            if (PlatformObjectUtils.isNotEmpty(calculationTasks.getStructuralFourProgress()) && "0".equals(calculationTasks.getStructuralFourProgress())) {
                throw new RuntimeException("请先计算结构破坏-四个概率水准的确认评估！");
            }
        } else {
            throw new RuntimeException("参数错误，请联系管理员！");
        }

        //获取网格中各结构类型不同房屋用途占比（备用如果原房屋格网中各个房屋用途占比均为0但是总面积不为0时使用）
        List<StructureHouseUsingPercent> percentList = casualtiesDERepository.getStructureHouseUsingPercent();
        //如果为网格数据
        if ("1".equals(calculationTasks.getHouseDataFlag())) {
            //查询版本信息获取dataType
            List<DictEntityVo> dictItemByDictId = dictItemService.getDictItemByDictCode("jzwglgwlx");
            //if ("0".equals(calculationTasks.getRadio2())) {
                //获取评估区域的省市县
                List<PCC> list = calculationTasks.getList();
                if ("0".equals(seismicInputMode)) {
                    //烈度
                    //按省市县确定评估区域
                    int num = 0;
                    if (PlatformObjectUtils.isNotEmpty(list)) {
                        //获取所有省市县的易损性数据
                        for (PCC pcc : list) {
                            //获取当前区县的易损性数据
                            Map<String, Map<String, Map<String, BuildingVulnerability>>> ysxTable = ySXUtil.getYSX(calculationTasks.getId(), pcc.getPpName(), pcc.getCityName(), pcc.getName());
                            List<CasualtiesResult> centerResultList = centerEvaluate(pcc, dictItemByDictId,
                                    calculationTasks, null, "", "0", percentList, seismicInputMode,ysxTable);
                            if (centerResultList.size() > 0) {
                                num++;
                                //根据人口版本获取人口数据
                                List<LinkedHashMap> popoluationList = getPopoluationList(calculationTasks.getPopluationVersion(), pcc);
                                if (PlatformObjectUtils.isEmpty(popoluationList) || popoluationList.size() == 0) {
                                    throw new RuntimeException("计算失败，人口格网版本为" + calculationTasks.getPopluationVersion() + "下获取不到" + pcc.getPpName() + "-" + pcc.getCityName() + "_" + pcc.getName() + "的人口数据");
                                }
                                getSameGridData(centerResultList, "1", popoluationList);
                            }
                        }
                    }
                    if(num==0){
                        throw new RuntimeException("计算未完成，该区域没有获取到任何房屋数据，没有生成评估结果");
                    }
                } else if ("1".equals(seismicInputMode)) {
                    version = calculationTasks.getFourProbabilisticVersions();
                    List<CasualtiesResult> finalResultList = new ArrayList<>();
                    List<LinkedHashMap> popoluationList = new ArrayList<>();
                    for (PCC pcc : list) {
                        //四个概率水准
                        if (org.apache.commons.lang3.StringUtils.isBlank(version)) {
                            version = "JC02DZQH20230810002";
                        }
                        //获取四个标准概率水准数据
                        List<ProbabilityLevel> intensityList = getLdAndPgaData(version, type, pcc);
                        //List<ProbabilityLevel> intensityList = getLdAndPgaDataFromFxqh(version, type, pcc);
                        if(PlatformObjectUtils.isEmpty(intensityList) || intensityList.size()==0){
                            throw new RuntimeException("计算未完成,无法获取到版本为"+version+"的四个概率水准数据");
                        }
                        finalResultList.addAll(this.handlePgaIntensity(intensityList, pcc, dictItemByDictId,
                                calculationTasks, type, percentList, version, seismicInputMode));
                        //根据人口版本获取人口数据
                        List<LinkedHashMap> popList = getPopoluationList(calculationTasks.getPopluationVersion(), pcc);
                        if (PlatformObjectUtils.isEmpty(popList) || popList.size() == 0) {
                            throw new RuntimeException("计算失败，人口格网版本为" + calculationTasks.getPopluationVersion() + "下获取不到" + pcc.getPpName() + "-" + pcc.getCityName() + "_" + pcc.getName() + "的人口数据");
                        }
                        popoluationList.addAll(popList);
                    }
                    if (finalResultList.size() > 0) {
                        getSameGridDataForPga(finalResultList, "1", popoluationList);
                    }else{
                        throw new RuntimeException("计算未完成，该区域没有获取到任何房屋数据，没有生成评估结果");
                    }
                } else if ("2".equals(seismicInputMode)) {
                    //地震影响场版本
                    //String version = calculationTasks.getInfluenceFieldVersion();
                    String influenceVersion = version;
                    if (PlatformObjectUtils.isEmpty(influenceVersion)) {
                        influenceVersion = "20230810163644YXC001";
                    }
                    Map<String, Map<String, Map<String, Map<String, BuildingVulnerability>>>>  influenceMap = new HashMap<>();
                    //获取影响场信息
                    List<SettingInfluenceFliedEntity> influenceList = seismicImpactFieldRepository.getInfluencefliedById(influenceVersion);
                    if (PlatformObjectUtils.isNotEmpty(influenceList) && influenceList.size() > 0) {
                        List<CasualtiesResult> influenceResultList = new ArrayList<>();
                        for (SettingInfluenceFliedEntity earthquakeAffected : influenceList) {
                            //查询在该影响场烈度中的格网信息
                            for (PCC pcc : list) {
                                //获取当前区县的易损性数据
                                Map<String, Map<String, Map<String, BuildingVulnerability>>> ysxTable = null;
                                if(influenceMap.containsKey(pcc.getPpName()+"_"+pcc.getCityName()+"_"+pcc.getName())){
                                    ysxTable = influenceMap.get(pcc.getPpName()+"_"+pcc.getCityName()+"_"+pcc.getName());
                                }else{
                                    ysxTable =  ySXUtil.getYSX(calculationTasks.getId(), pcc.getPpName(), pcc.getCityName(), pcc.getName());
                                    influenceMap.put(pcc.getPpName()+"_"+pcc.getCityName()+"_"+pcc.getName(),ysxTable);
                                }
                                List<CasualtiesResult> centerResultList = centerEvaluate(pcc, dictItemByDictId,
                                        calculationTasks, earthquakeAffected, version, "2", percentList, seismicInputMode,ysxTable);
                                if (centerResultList.size() > 0) {
                                    influenceResultList.addAll(centerResultList);
                                }
                            }
                        }
                        if (influenceResultList.size() > 0) {
                            List<LinkedHashMap> popoluationList = getPopoluationList(calculationTasks.getPopluationVersion(), null);
                            if (PlatformObjectUtils.isEmpty(popoluationList) || popoluationList.size() == 0) {
                                throw new RuntimeException("计算失败，人口格网版本为" + calculationTasks.getPopluationVersion() + "下获取不到人口数据");
                            }
                            getSameGridData(influenceResultList, "2", popoluationList);
                            this.calculationIntensity(version, assessId);
                        }else{
                            throw new RuntimeException("计算未完成，该区域没有获取到任何房屋数据，没有生成评估结果");
                        }
                    }
                }
            //}
//            else {
//                //获取13张格网数据
//                List<Grid13VO> grid13VOList = centerEvaluate1(dictItemByDictId, calculationTasks, version,
//                        percentList, seismicInputMode);
//                //根据字典值获取不同结构类型的具体数据并计算
//                Map<String, Map<String, Map<String, Map<String, BuildingVulnerability>>>> map = new HashMap<>();
//                //存取所有的网格信息结果用于保存
//                List<CasualtiesResult> finalResultList = new ArrayList<>();
//                //存放的是人口网格信息
//                List<LinkedHashMap> popoluationList = new ArrayList<>();
//                //存放的是四个概率水准的数据
//                List<ProbabilityLevel> probabilityLevelList = new ArrayList<>();
//                Map<String, ProbabilityLevel> proMap = new HashMap<>();
//                if (PlatformObjectUtils.isNotEmpty(grid13VOList) && grid13VOList.size() > 0) {
//                    for (Grid13VO obj : grid13VOList) {
//                        if (PlatformObjectUtils.isEmpty(obj.getProvince()) || PlatformObjectUtils.isEmpty(obj.getCity()) || PlatformObjectUtils.isEmpty(obj.getCounty())) {
//                            continue;
//                        }
//                        Map<String, Map<String, Map<String, BuildingVulnerability>>> ysxTable = null;
//                        //根据网格的省市县查询数据
//                        if (!map.containsKey(obj.getProvince() + "-" + obj.getCity() + "-" + obj.getCounty())) {
//                            PCC pcc = new PCC();
//                            pcc.setPpName(obj.getProvince());
//                            pcc.setCityName(obj.getCity());
//                            pcc.setName(obj.getCounty());
//                            //查询易损性数据
//                            ysxTable = ySXUtil.getYSX(calculationTasks.getId(), obj.getProvince(), obj.getCity(), obj.getCounty());
//                            map.put(calculationTasks.getId() + "-" + obj.getProvince() + "-" + obj.getCity() + "-" + obj.getCounty(), ysxTable);
//                            //获取区县的人口格网数据
//                            List<LinkedHashMap> popList = getPopoluationList(calculationTasks.getPopluationVersion(), pcc);
//                            if (PlatformObjectUtils.isEmpty(popList) || popList.size() == 0) {
//                                throw new RuntimeException("计算失败，人口格网版本为" + calculationTasks.getPopluationVersion() + "下获取不到" + pcc.getPpName() + "-" + pcc.getCityName() + "_" + pcc.getName() + "的人口数据");
//                            }
//                            popoluationList.addAll(popList);
//                            if ("1".equals(seismicInputMode)) {
//                                //表示是四个概率水准
//                                List<ProbabilityLevel> intensityList = getLdAndPgaData(version, type, pcc);
//                                if (PlatformObjectUtils.isEmpty(intensityList) || intensityList.size() == 0) {
//                                    throw new RuntimeException("计算失败，版本为" + version + "下获取不到" + pcc.getPpName() + "-" + pcc.getCityName() + "_" + pcc.getName() + "的四个概率水准数据");
//                                }
//                                proMap = intensityList.stream().collect(Collectors.toMap(ProbabilityLevel::getExtends1, Function.identity()));
//                                probabilityLevelList.addAll(intensityList);
//                            }
//                        } else {
//                            ysxTable = map.get(obj.getProvince() + "-" + obj.getCity() + "-" + obj.getCounty());
//                        }
//                        SettingInfluenceFliedEntity earthquakeAffected = null;
//                        if ("1".equals(seismicInputMode)) {
//                            earthquakeAffected = new SettingInfluenceFliedEntity();
//                            //四个概率
//                            ProbabilityLevel probabilityLevel = proMap.get(obj.getExtends1());
//                            if (PlatformObjectUtils.isEmpty(probabilityLevel)) {
//                                continue;
//                            }
//                            earthquakeAffected.setDzIntensity(getPgaIntensity(probabilityLevel, type));
//                            String pga = "sgglsz1";
//                            earthquakeAffected.setId(pga);
//                        } else if ("2".equals(seismicInputMode)) {
//                            //影响场  obj已经确定影响场的烈度 所以直接计算对应烈度的即可
//                            earthquakeAffected = new SettingInfluenceFliedEntity();
//                            earthquakeAffected.setDzIntensity(obj.getIntensity());
//                        }
//                        List<CasualtiesResult> ywData = getYwData1(obj, ysxTable, calculationTasks,
//                                earthquakeAffected, version, percentList, seismicInputMode);
//                        if (PlatformObjectUtils.isNotEmpty(ywData) && ywData.size() > 0) {
//                            finalResultList.addAll(ywData);
//                        }
//                    }
//                }else{
//                    throw new RuntimeException("计算未完成，该区域没有获取到任何房屋数据，没有生成评估结果");
//                }
//                if (PlatformObjectUtils.isNotEmpty(finalResultList) && finalResultList.size() > 0) {
//                    if ("0".equals(seismicInputMode)) {
//                        //烈度
//                        getSameGridData(finalResultList, "1", popoluationList);
//                    } else if ("2".equals(seismicInputMode)) {
//                        //影响场
//                        getSameGridData(finalResultList, "2", popoluationList);
//                    } else {
//                        //计算的概率水准
//                        getSameGridData(finalResultList, "1", popoluationList);
//                    }
//                }
//            }
        } else if ("0".equals(calculationTasks.getHouseDataFlag())) {
            //查询字典项
            Map<Object, Object> map = redisTemplate.opsForHash().entries("FXQH:" + FxfzConstants.CACHE_SYS_KEY + "dictItemMapForEvaluate");
            if (map == null || map.values().size() == 0) {
                map = dictItemService.getDictItemMap();
            }
            if ("0".equals(calculationTasks.getRadio2())) {
                List<PCC> list = calculationTasks.getList();
                List<CasualtiesResult> calculationList = new ArrayList<>();
                if (PlatformObjectUtils.isNotEmpty(list) && list.size() > 0) {
                    if ("0".equals(seismicInputMode)) {
                        //烈度
                        int num = 0;
                        for (PCC pcc : list) {
                            List<LinkedHashMap> popoluationList = getPopoluationList(calculationTasks.getPopluationVersion(), pcc);
                            if (PlatformObjectUtils.isEmpty(popoluationList) || popoluationList.size() == 0) {
                                throw new RuntimeException("计算失败，人口格网版本为" + calculationTasks.getPopluationVersion() + "下获取不到" + pcc.getPpName() + "-" + pcc.getCityName() + "_" + pcc.getName() + "的人口数据");
                            }
                            //求房屋单体房屋内人员的密度过程的中间结果
                            Map<String, BigDecimal> popMap = buildGridMap(popoluationList, calculationTasks.getHouseData(), pcc, null);
                            if (popMap.values().size() == 0) {
                                throw new RuntimeException("计算失败，无法根据人口数据匹配到房屋单体数据");
                            }
                            //获取当前区县的易损性数据
                            Map<String, Map<String, Map<String, BuildingVulnerability>>> ysxTable = ySXUtil.getYSX(calculationTasks.getId(), pcc.getPpName(), pcc.getCityName(), pcc.getName());
                            //获取当前区县的房屋单体数据
                            List<BuildingIndividualEntity> buildingIndividualEntities = buildingIndividualRepository.getAllWithGeom(calculationTasks.getHouseData(), "", pcc.getPpName(), pcc.getCityName(), pcc.getName());
//                            if (PlatformObjectUtils.isEmpty(buildingIndividualEntities) && buildingIndividualEntities.size() == 0) {
//                                throw new RuntimeException("计算未完成,请维护" + pcc.getPpName() + "-" + pcc.getCityName() + "-" + pcc.getName() + "的房屋单体数据");
//                            }
                            if(buildingIndividualEntities.size()>0){
                                num++;
                            }
                            //组织并保存数据
                            publicOperateSave(version, calculationTasks, map, popMap, calculationList,
                                    buildingIndividualEntities, ysxTable, pcc, null, seismicInputMode);
                        }
                        if(num==0){
                           throw new RuntimeException("计算未完成，该区域没有获取到任何房屋数据，没有生成评估结果");
                        }
                    } else if ("1".equals(seismicInputMode)) {
                        //四个概率水准
                        if (org.apache.commons.lang3.StringUtils.isBlank(version)) {
                            version = "JC02DZQH20230810002";
                        }
                        int num = 0;
                        for (PCC pcc : list) {
                            //求房屋单体房屋内人员的密度过程的中间结果
                            List<LinkedHashMap> popoluationList = getPopoluationList(calculationTasks.getPopluationVersion(), pcc);
                            if (PlatformObjectUtils.isEmpty(popoluationList) || popoluationList.size() == 0) {
                                throw new RuntimeException("计算失败，人口格网版本为" + calculationTasks.getPopluationVersion() + "下获取不到" + pcc.getPpName() + "-" + pcc.getCityName() + "_" + pcc.getName() + "的人口数据");
                            }
                            Map<String, BigDecimal> popMap = buildGridMap(popoluationList, calculationTasks.getHouseData(), pcc, null);
                            if (popMap.values().size() == 0) {
                                throw new RuntimeException("计算失败，无法根据人口数据匹配到房屋单体数据");
                            }
                            //获取当前区县的易损性数据
                            Map<String, Map<String, Map<String, BuildingVulnerability>>> ysxTable = ySXUtil.getYSX(calculationTasks.getId(), pcc.getPpName(), pcc.getCityName(), pcc.getName());
                            //获取四个标准概率水准数据
                            List<ProbabilityLevel> intensityList = getLdAndPgaData(version, type, pcc);
                            if (intensityList.size() > 0) {
                                for (ProbabilityLevel probabilityLevel : intensityList) {
                                    SettingInfluenceFliedEntity field = new SettingInfluenceFliedEntity();
                                    String pgaIntensity = getPgaIntensity(probabilityLevel, type);
                                    field.setDzIntensity(pgaIntensity);
                                    String pga = "sgglsz1";
                                    field.setId(pga);
                                    //获取在该ld或pga数据中的所有的房屋单体数据
                                    List<BuildingIndividualEntity> buildingList = buildingIndividualRepository.getAllWithGeom(calculationTasks.getHouseData(), probabilityLevel.getGeom(), pcc.getPpName(), pcc.getCityName(), pcc.getName());
                                    if (PlatformObjectUtils.isNotEmpty(buildingList) && buildingList.size() > 0) {
                                        num++;
                                        publicOperateSave(version, calculationTasks, map, popMap, calculationList,
                                                buildingList, ysxTable, pcc, field, seismicInputMode);
                                    }
                                }
                            }
//                            else {
//                                throw new RuntimeException("计算未完成,获取不到" + pcc.getPpName() + "-" + pcc.getCityName() + "-" + pcc.getName() + "的四个概率水准数据");
//                            }
                        }
                        if(num==0){
                           throw new RuntimeException("计算未完成，该区域没有获取到任何房屋数据，没有生成评估结果");
                        }
                    } else if ("2".equals(seismicInputMode)) {
                        //影响场
                        //地震影响场版本
                        String influenceVersion = version;
                        int num = 0;
                        //获取影响场信息
                        List<SettingInfluenceFliedEntity> influenceList = seismicImpactFieldRepository.getInfluencefliedById(influenceVersion);
                        if (PlatformObjectUtils.isNotEmpty(influenceList) && influenceList.size() > 0) {
                            List<CasualtiesResult> influenceResultList = new ArrayList<>();
                            for (PCC pcc : list) {
                                //求房屋单体房屋内人员的密度过程的中间结果
                                List<LinkedHashMap> popoluationList = getPopoluationList(calculationTasks.getPopluationVersion(), pcc);
                                if (PlatformObjectUtils.isEmpty(popoluationList) || popoluationList.size() == 0) {
                                    throw new RuntimeException("计算失败，人口格网版本为" + calculationTasks.getPopluationVersion() + "下获取不到" + pcc.getPpName() + "-" + pcc.getCityName() + "_" + pcc.getName() + "的人口数据");
                                }
                                Map<String, BigDecimal> popMap = buildGridMap(popoluationList, calculationTasks.getHouseData(), pcc, null);
                                if (popMap.values().size() == 0) {
                                    throw new RuntimeException("计算失败，无法根据人口数据匹配到房屋单体数据");
                                }
                                for (SettingInfluenceFliedEntity earthquakeAffected : influenceList) {
                                    //获取当前区县的易损性数据
                                    Map<String, Map<String, Map<String, BuildingVulnerability>>> ysxTable = ySXUtil.getYSX(calculationTasks.getId(), pcc.getPpName(), pcc.getCityName(), pcc.getName());
                                    //获取在该影响场数据中的所有的房屋单体数据
                                    List<BuildingIndividualEntity> buildingList = buildingIndividualRepository.getAllWithGeom(calculationTasks.getHouseData(), earthquakeAffected.getGeom(), pcc.getPpName(), pcc.getCityName(), pcc.getName());
                                    if (PlatformObjectUtils.isNotEmpty(buildingList) && buildingList.size() > 0) {
                                        num++;
                                        publicOperateSave(version, calculationTasks, map, popMap, calculationList,
                                                buildingList, ysxTable, pcc, null, seismicInputMode);
                                    }
                                }
                            }
                        }
                        if(num==0){
                            throw new RuntimeException("计算未完成，该区域没有获取到任何房屋数据，没有生成评估结果");
                        }
                    }
                }
                if (calculationList.size() > 0) {
                    casualtiesDERepository.batchSaveCasualtyResult(calculationList);
                }
            } else {
                //获取房屋单体数据
                List<BuildingIndividualEntity> buildingIndividualEntityList = centerEvaluate2(calculationTasks,
                        version, seismicInputMode);
                //根据字典值获取不同结构类型的具体数据并计算
                Map<String, Map<String, Map<String, Map<String, BuildingVulnerability>>>> bmap = new HashMap<>();
                //存取所有的网格信息结果用于保存
                List<CasualtiesResult> calculationList = new ArrayList<>();
                //存放的是人口网格信息
                List<LinkedHashMap> popoluationList = new ArrayList<>();
                //存放的是四个概率水准的数据
                List<ProbabilityLevel> probabilityLevelList = new ArrayList<>();
                Map<String, List<ProbabilityLevel>> proMap = new HashMap<>();
                Map<String, BigDecimal> popMap = new HashMap<>();
                if (PlatformObjectUtils.isNotEmpty(buildingIndividualEntityList) && buildingIndividualEntityList.size() > 0) {
                    List<String> districts = buildingIndividualEntityList.stream().map(buildingIndividualEntity -> buildingIndividualEntity.getProvince() + "-" + buildingIndividualEntity.getCity() + "-" + buildingIndividualEntity.getCounty()).distinct().collect(Collectors.toList());
                    if (PlatformObjectUtils.isNotEmpty(districts) && districts.size() > 0) {
                        for (String district : districts) {
                            PCC pcc = new PCC();
                            pcc.setPpName(district.split("-")[0]);
                            pcc.setCityName(district.split("-")[1]);
                            pcc.setName(district.split("-")[2]);
                            //获取区县的人口格网数据
                            List<LinkedHashMap> popList = getPopoluationList(calculationTasks.getPopluationVersion(), pcc);
//                            if(PlatformObjectUtils.isEmpty(popoluationList) || popoluationList.size()==0){
//                                throw new RuntimeException("计算失败，人口格网版本为"+calculationTasks.getPopluationVersion()+"下获取不到"+pcc.getPpName()+"-"+pcc.getCityName()+"_"+pcc.getName()+"的人口数据");
//                            }
                            buildGridMap(popList, calculationTasks.getHouseData(), pcc, popMap);
                            if (popMap.values().size() == 0) {
                                throw new RuntimeException("计算失败，无法根据人口数据匹配到房屋单体数据");
                            }
                        }
                    }
                    for (BuildingIndividualEntity obj : buildingIndividualEntityList) {
                        //四个概率水准实体
                        ProbabilityLevel probabilityLevel = null;
                        if (PlatformObjectUtils.isEmpty(obj.getProvince()) || PlatformObjectUtils.isEmpty(obj.getCity()) || PlatformObjectUtils.isEmpty(obj.getCounty())) {
                            continue;
                        }
                        Map<String, Map<String, Map<String, BuildingVulnerability>>> ysxTable = null;
                        //根据网格的省市县查询数据
                        if (!bmap.containsKey(obj.getProvince() + "-" + obj.getCity() + "-" + obj.getCounty())) {
                            PCC pcc = new PCC();
                            pcc.setPpName(obj.getProvince());
                            pcc.setCityName(obj.getCity());
                            pcc.setName(obj.getCounty());
                            //查询易损性数据
                            ysxTable = ySXUtil.getYSX(calculationTasks.getId(), obj.getProvince(), obj.getCity(), obj.getCounty());
                            bmap.put(obj.getProvince() + "-" + obj.getCity() + "-" + obj.getCounty(), ysxTable);
                            if ("1".equals(seismicInputMode)) {
                                //表示是四个概率水准
                                List<ProbabilityLevel> intensityList = null;
                                if (!proMap.containsKey(pcc.getPpName() + "-" + pcc.getCityName() + "-" + pcc.getName())) {
                                    intensityList = getLdAndPgaData(version, type, pcc);
                                    proMap.put(pcc.getPpName() + "-" + pcc.getCityName() + "-" + pcc.getName(), intensityList);
                                } else {
                                    intensityList = proMap.get(pcc.getPpName() + "-" + pcc.getCityName() + "-" + pcc.getName());
                                }
                                if (PlatformObjectUtils.isEmpty(intensityList) || intensityList.size() == 0) {
                                    throw new RuntimeException("计算失败，版本为" + version + "下获取不到" + pcc.getPpName() + "-" + pcc.getCityName() + "_" + pcc.getName() + "的四个概率水准数据");
                                }

                                for (ProbabilityLevel e : intensityList) {
                                    if (economicLossEDRepository.getSTIntersects(e.getGeom(), BigDecimal.valueOf(obj.getLongitude()),
                                            BigDecimal.valueOf(obj.getLatitude()))) {
                                        probabilityLevel = e;
                                        break;
                                    }
                                }
                                if (probabilityLevel == null) {
                                    continue;
                                }
                            }

                        } else {
                            ysxTable = bmap.get(obj.getProvince() + "-" + obj.getCity() + "-" + obj.getCounty());
                            List<ProbabilityLevel> intensityList = proMap.get(obj.getProvince() + "-" + obj.getCity() + "-" + obj.getCounty());
                            for (ProbabilityLevel e : intensityList) {
                                if (economicLossEDRepository.getSTIntersects(e.getGeom(), BigDecimal.valueOf(obj.getLongitude()),
                                        BigDecimal.valueOf(obj.getLatitude()))) {
                                    probabilityLevel = e;
                                    break;
                                }
                            }
                        }
                        if ("1".equals(seismicInputMode)) {
                            for(int i=1;i<5;i++){
                                SettingInfluenceFliedEntity earthquakeAffected = new SettingInfluenceFliedEntity();
                                //四个概率
                                earthquakeAffected.setDzIntensity(getPgaIntensity(probabilityLevel, type));
                                String pga = "sgglsz"+i;
                                earthquakeAffected.setId(pga);
                                publicOperateSave1(version, calculationTasks, map, popMap, calculationList, obj, ysxTable,
                                        earthquakeAffected, seismicInputMode);
                            }
                        } else if ("2".equals(seismicInputMode)) {
                            //影响场  obj已经确定影响场的烈度 所以直接计算对应烈度的即可
                            SettingInfluenceFliedEntity earthquakeAffected = new SettingInfluenceFliedEntity();
                            earthquakeAffected.setDzIntensity(obj.getIntensity());
                            publicOperateSave1(version, calculationTasks, map, popMap, calculationList, obj, ysxTable,
                                    earthquakeAffected, seismicInputMode);
                        }

                    }
                }else{
                    throw new RuntimeException("计算未完成，该区域没有获取到任何房屋数据，没有生成评估结果");
                }
                if (calculationList.size() > 0) {
                    casualtiesDERepository.batchSaveCasualtyResult(calculationList);
                }
            }
            //更新计算进度
            if (seismicInputMode.equals("0")) {
                calculationTasksRepository.updateLdProgress(assessId, "评估", "人员伤亡");
            }
            if (seismicInputMode.equals("1")) {
                calculationTasksRepository.updateFourProbabilisticProgress(assessId, "评估", "人员伤亡");
            }
            if (seismicInputMode.equals("2")) {
                calculationTasksRepository.updateStructuralFieldProgress(assessId, "评估", "人员伤亡");
            }
            boolean bool = hypergraphService.getWorkspaceReload("fxqh_casualties_calculation_ed");
        }
    }
//     public void calculation1(String assessId, String version, String type) throws Exception {
//         //先删除这个评估记录之前生成的结果
//         casualtiesDERepository.deleteEvaluateResult1(assessId);
//         CasualtiesDE casualtiesDE = this.getById(assessId);
//         if (PlatformObjectUtils.isEmpty(casualtiesDE)) {
//             throw new RuntimeException("计算失败，查询不到评估记录信息");
//         }
//
//         //获取网格中各结构类型不同房屋用途占比（备用如果原房屋格网中各个房屋用途占比均为0但是总面积不为0时使用）
//         List<StructureHouseUsingPercent> percentList = casualtiesDERepository.getStructureHouseUsingPercent();
//         //如果为网格数据
//         if ("1".equals(casualtiesDE.getHouseDataFlag())) {
//             //查询版本信息获取dataType
//             List<DictEntityVo> dictItemByDictId = dictItemService.getDictItemByDictId("jzwglgwlx");
//             if ("0".equals(casualtiesDE.getRadio2())) {
//                 //获取评估区域的省市县
//                 List<PCC> list = casualtiesDE.getList();
//                 if ("0".equals(casualtiesDE.getSeismicInputMode())) {
//                     //烈度
//                     //按省市县确定评估区域
//                     if (PlatformObjectUtils.isNotEmpty(list)) {
//                         //获取所有省市县的易损性数据
//                         for (PCC pcc : list) {
//                             List<CasualtiesResult> centerResultList = centerEvaluate(pcc, dictItemByDictId, casualtiesDE, null, "", "0", percentList);
//                             if (centerResultList.size() > 0) {
//                                 //根据人口版本获取人口数据
//                                 List<LinkedHashMap> popoluationList = getPopoluationList(casualtiesDE.getPopluationVersion(),pcc);
//                                 if(PlatformObjectUtils.isEmpty(popoluationList) || popoluationList.size()==0){
//                                     throw new RuntimeException("计算失败，人口格网版本为"+casualtiesDE.getPopluationVersion()+"下获取不到"+pcc.getPpName()+"-"+pcc.getCityName()+"_"+pcc.getName()+"的人口数据");
//                                 }
//                                 getSameGridData(centerResultList, "1", popoluationList);
//                             }
//                         }
//                     }
//                     //刷新指定超图工作空间数据源数据集
//                     boolean bool = hypergraphService.getWorkspaceReload("fxqh_casualties_calculation_ed");
//                 } else if ("1".equals(casualtiesDE.getSeismicInputMode())) {
//                     List<CasualtiesResult> finalResultList = new ArrayList<>();
//                     List<LinkedHashMap> popoluationList = new ArrayList<>();
//                     for (PCC pcc : list) {
//                         //四个概率水准
//                         if (org.apache.commons.lang3.StringUtils.isBlank(version)) {
//                             version = "JC02DZQH20230810002";
//                         }
//                         //获取四个标准概率水准数据
//                         List<ProbabilityLevel> intensityList = getLdAndPgaData(version, type, pcc);
//                         if (intensityList.size() > 0) {
//                             finalResultList.addAll(this.handlePgaIntensity(intensityList, pcc, dictItemByDictId, casualtiesDE, type, percentList, version));
//                         }
//                         //根据人口版本获取人口数据
//                         List<LinkedHashMap> popList = getPopoluationList(casualtiesDE.getPopluationVersion(),pcc);
//                         if(PlatformObjectUtils.isEmpty(popList) || popList.size()==0){
//                             throw new RuntimeException("计算失败，人口格网版本为"+casualtiesDE.getPopluationVersion()+"下获取不到"+pcc.getPpName()+"-"+pcc.getCityName()+"_"+pcc.getName()+"的人口数据");
//                         }
//                         popoluationList.addAll(popList);
//                     }
//                     if (finalResultList.size() > 0) {
//                         getSameGridDataForPga(finalResultList, "1", popoluationList);
//                     }
//                     boolean bool = hypergraphService.getWorkspaceReload("fxqh_casualties_calculation_ed");
//                 } else if ("2".equals(casualtiesDE.getSeismicInputMode())) {
//                     //地震影响场版本
//                     String influenceVersion = version;
//                     if(PlatformObjectUtils.isEmpty(influenceVersion)){
//                         influenceVersion = "20230810163644YXC001";
//                     }
//                     //获取影响场信息
//                     List<SettingInfluenceFliedEntity> influenceList = seismicImpactFieldRepository.getInfluencefliedById(influenceVersion);
//                     if (PlatformObjectUtils.isNotEmpty(influenceList) && influenceList.size() > 0) {
//                         List<CasualtiesResult> influenceResultList = new ArrayList<>();
//                         for (SettingInfluenceFliedEntity earthquakeAffected : influenceList) {
//                             //查询在该影响场烈度中的格网信息
//                             for (PCC pcc : list) {
//                                 List<CasualtiesResult> centerResultList = centerEvaluate(pcc, dictItemByDictId, casualtiesDE, earthquakeAffected, version, "2", percentList);
//                                 if (centerResultList.size() > 0) {
//                                     influenceResultList.addAll(centerResultList);
//                                 }
//                             }
//                         }
//                         if (influenceResultList.size() > 0) {
//                             List<LinkedHashMap> popoluationList = getPopoluationList(casualtiesDE.getPopluationVersion(),null);
//                             if(PlatformObjectUtils.isEmpty(popoluationList) || popoluationList.size()==0){
//                                 throw new RuntimeException("计算失败，人口格网版本为"+casualtiesDE.getPopluationVersion()+"下获取不到人口数据");
//                             }
//                             getSameGridData(influenceResultList, "2", popoluationList);
//                         }
//                     }
//                 }
//             }else{
//                 //获取13张格网数据
//                 List<Grid13VO> grid13VOList = centerEvaluate1(dictItemByDictId, casualtiesDE, version,  percentList);
//                 //根据字典值获取不同结构类型的具体数据并计算
//                 Map<String,Table<String, String, List<BuildingVulnerability>>> map = new HashMap<>();
//                 //存取所有的网格信息结果用于保存
//                 List<CasualtiesResult> finalResultList = new ArrayList<>();
//                 //存放的是人口网格信息
//                 List<LinkedHashMap> popoluationList = new ArrayList<>();
//                 //存放的是四个概率水准的数据
//                 List<ProbabilityLevel> probabilityLevelList= new ArrayList<>();
//                 Map<String, ProbabilityLevel> proMap = new HashMap<>();
//                 if (PlatformObjectUtils.isNotEmpty(grid13VOList) && grid13VOList.size() > 0) {
//                     for (Grid13VO obj : grid13VOList) {
//                         if (PlatformObjectUtils.isEmpty(obj.getProvince())||PlatformObjectUtils.isEmpty(obj.getCity())||PlatformObjectUtils.isEmpty(obj.getCounty())){
//                             continue;
//                         }
//                         Table<String, String, List<BuildingVulnerability>> ysxTable = null;
//                         //根据网格的省市县查询数据
//                         if(!map.containsKey(obj.getProvince()+"-"+obj.getCity()+"-"+obj.getCounty())){
//                             PCC pcc = new PCC();
//                             pcc.setPpName(obj.getProvince());
//                             pcc.setCityName(obj.getCity());
//                             pcc.setName(obj.getCounty());
//                             //查询易损性数据
//                             ysxTable =  handleYsxData(pcc);
//                             map.put(obj.getProvince()+"-"+obj.getCity()+"-"+obj.getCounty(),ysxTable);
//                             //获取区县的人口格网数据
//                             List<LinkedHashMap> popList = getPopoluationList(casualtiesDE.getPopluationVersion(),pcc);
//                             if(PlatformObjectUtils.isEmpty(popList) || popList.size()==0){
//                                 throw new RuntimeException("计算失败，人口格网版本为"+casualtiesDE.getPopluationVersion()+"下获取不到"+pcc.getPpName()+"-"+pcc.getCityName()+"_"+pcc.getName()+"的人口数据");
//                             }
//                             popoluationList.addAll(popList);
//                             if("1".equals(casualtiesDE.getSeismicInputMode())){
//                                 //表示是四个概率水准
//                                 List<ProbabilityLevel> intensityList = getLdAndPgaData(version, type, pcc);
//                                 if(PlatformObjectUtils.isEmpty(intensityList) || intensityList.size()==0){
//                                     throw new RuntimeException("计算失败，版本为"+version+"下获取不到"+pcc.getPpName()+"-"+pcc.getCityName()+"_"+pcc.getName()+"的四个概率水准数据");
//                                 }
//                                 proMap = intensityList.stream().collect(Collectors.toMap(ProbabilityLevel::getExtends1, Function.identity()));
//                                 probabilityLevelList.addAll(intensityList);
//                             }
//                         }else{
//                             ysxTable =  map.get(obj.getProvince()+"-"+obj.getCity()+"-"+obj.getCounty());
//                         }
//                         SettingInfluenceFliedEntity earthquakeAffected = null;
//                         if("1".equals(casualtiesDE.getSeismicInputMode())){
//                             earthquakeAffected = new SettingInfluenceFliedEntity();
//                             //四个概率
//                             ProbabilityLevel probabilityLevel = proMap.get(obj.getExtends1());
//                             if(PlatformObjectUtils.isEmpty(probabilityLevel)){
//                                 continue;
//                             }
//                             earthquakeAffected.setDzIntensity(getPgaIntensity(probabilityLevel, type));
//                             String pga = "sgglsz1";
//                             earthquakeAffected.setId(pga);
//                         }else if("2".equals(casualtiesDE.getSeismicInputMode())){
//                             //影响场  obj已经确定影响场的烈度 所以直接计算对应烈度的即可
//                             earthquakeAffected = new SettingInfluenceFliedEntity();
//                             earthquakeAffected.setDzIntensity(obj.getIntensity());
//                         }
//                         List<CasualtiesResult> ywData = getYwData1(obj, ysxTable, casualtiesDE, earthquakeAffected, version, percentList);
//                         if(PlatformObjectUtils.isNotEmpty(ywData) && ywData.size()>0){
//                             finalResultList.addAll(ywData);
//                         }
//                     }
//                 }
//                 if(PlatformObjectUtils.isNotEmpty(finalResultList) && finalResultList.size()>0){
//                     if("0".equals(casualtiesDE.getSeismicInputMode())){
//                        //烈度
//                         getSameGridData(finalResultList, "1", popoluationList);
//                     }else  if("2".equals(casualtiesDE.getSeismicInputMode())){
//                         //影响场
//                         getSameGridData(finalResultList, "2", popoluationList);
//                     }else{
//                         //计算的概率水准
//                         getSameGridData(finalResultList,"1",popoluationList);
//                     }
//                 }
//             }
//         }else if("0".equals(casualtiesDE.getHouseDataFlag())){
//             //查询字典项
//             Map<Object, Object> map = redisTemplate.opsForHash().entries("FXQH:" + FxfzConstants.CACHE_SYS_KEY + "dictItemMapForEvaluate");
//             if(map==null || map.values().size()==0){
//                 map = dictItemService.getDictItemMap();
//             }
//             if ("0".equals(casualtiesDE.getRadio2())) {
//                 List<PCC> list = casualtiesDE.getList();
//                 List<CasualtiesResult> calculationList = new ArrayList<>();
//                 if(PlatformObjectUtils.isNotEmpty(list) && list.size()>0){
//                     if("0".equals(casualtiesDE.getSeismicInputMode())){
//                         //烈度
//                         for(PCC pcc:list){
//                             List<LinkedHashMap> popoluationList = getPopoluationList(casualtiesDE.getPopluationVersion(),pcc);
//                             if(PlatformObjectUtils.isEmpty(popoluationList) || popoluationList.size()==0){
//                                 throw new RuntimeException("计算失败，人口格网版本为"+casualtiesDE.getPopluationVersion()+"下获取不到"+pcc.getPpName()+"-"+pcc.getCityName()+"_"+pcc.getName()+"的人口数据");
//                             }
//                             //求房屋单体房屋内人员的密度过程的中间结果
//                             Map<String,BigDecimal> popMap = buildGridMap(popoluationList,casualtiesDE.getHouseData(),pcc,null);
//                             if(popMap.values().size()==0){
//                                 throw new RuntimeException("计算失败，无法根据人口数据匹配到房屋单体数据");
//                             }
//                             //获取当前区县的易损性数据
//                             Table<String, String, List<BuildingVulnerability>> ysxTable =  handleYsxData(pcc);
//                             //获取当前区县的房屋单体数据
//                             List<BuildingIndividualEntity> buildingIndividualEntities =   buildingIndividualRepository.getAllWithGeom(casualtiesDE.getHouseData(),"",pcc.getPpName(),pcc.getCityName(),pcc.getName());
//                             if(PlatformObjectUtils.isEmpty(buildingIndividualEntities) && buildingIndividualEntities.size()==0){
//                                 throw new RuntimeException("计算未完成,请维护"+pcc.getPpName()+"-"+pcc.getCityName()+"-"+pcc.getName()+"的房屋单体数据");
//                             }
//                             //组织并保存数据
//                             publicOperateSave(version, casualtiesDE, map, popMap, calculationList, buildingIndividualEntities,ysxTable,pcc,null);
//                         }
//                     }else if("1".equals(casualtiesDE.getSeismicInputMode())){
//                         //四个概率水准
//                         if (org.apache.commons.lang3.StringUtils.isBlank(version)) {
//                             version = "JC02DZQH20230810002";
//                         }
//                         for(PCC pcc:list){
//                             //求房屋单体房屋内人员的密度过程的中间结果
//                             List<LinkedHashMap> popoluationList = getPopoluationList(casualtiesDE.getPopluationVersion(),pcc);
//                             if(PlatformObjectUtils.isEmpty(popoluationList) || popoluationList.size()==0){
//                                 throw new RuntimeException("计算失败，人口格网版本为"+casualtiesDE.getPopluationVersion()+"下获取不到"+pcc.getPpName()+"-"+pcc.getCityName()+"_"+pcc.getName()+"的人口数据");
//                             }
//                             Map<String,BigDecimal> popMap = buildGridMap(popoluationList,casualtiesDE.getHouseData(),pcc,null);
//                             if(popMap.values().size()==0){
//                                 throw new RuntimeException("计算失败，无法根据人口数据匹配到房屋单体数据");
//                             }
//                             //当前省市县的易损性数据
//                             Table<String, String, List<BuildingVulnerability>> ysxTable =  handleYsxData(pcc);
//                             //获取四个标准概率水准数据
//                             List<ProbabilityLevel> intensityList = getLdAndPgaData(version, type, pcc);
//                             if (intensityList.size() > 0) {
//                                 for (ProbabilityLevel probabilityLevel : intensityList) {
//                                     SettingInfluenceFliedEntity field = new SettingInfluenceFliedEntity();
//                                     String pgaIntensity = getPgaIntensity(probabilityLevel, type);
//                                     field.setDzIntensity(pgaIntensity);
//                                     String pga = "sgglsz1";
//                                     field.setId(pga);
//                                     //获取在该ld或pga数据中的所有的房屋单体数据
//                                     List<BuildingIndividualEntity> buildingList = buildingIndividualRepository.getAllWithGeom(casualtiesDE.getHouseData(),probabilityLevel.getGeom(),pcc.getPpName(),pcc.getCityName(),pcc.getName());
//                                     if(PlatformObjectUtils.isNotEmpty(buildingList) && buildingList.size()>0){
//                                         publicOperateSave(version, casualtiesDE, map, popMap, calculationList, buildingList,ysxTable,pcc,field);
//                                     }
//                                 }
//                             }else{
//                                 throw new RuntimeException("计算未完成,获取不到"+pcc.getPpName()+"-"+pcc.getCityName()+"-"+pcc.getName()+"的四个概率水准数据");
//                             }
//                         }
//                     }else if("2".equals(casualtiesDE.getSeismicInputMode())){
//                         //影响场
//                         //地震影响场版本
//                         String influenceVersion = version;
//                         //获取影响场信息
//                         List<SettingInfluenceFliedEntity> influenceList = seismicImpactFieldRepository.getInfluencefliedById(influenceVersion);
//                         if (PlatformObjectUtils.isNotEmpty(influenceList) && influenceList.size() > 0) {
//                             List<CasualtiesResult> influenceResultList = new ArrayList<>();
//                             for (PCC pcc : list) {
//                                 //求房屋单体房屋内人员的密度过程的中间结果
//                                 List<LinkedHashMap> popoluationList = getPopoluationList(casualtiesDE.getPopluationVersion(),pcc);
//                                 if(PlatformObjectUtils.isEmpty(popoluationList) || popoluationList.size()==0){
//                                     throw new RuntimeException("计算失败，人口格网版本为"+casualtiesDE.getPopluationVersion()+"下获取不到"+pcc.getPpName()+"-"+pcc.getCityName()+"_"+pcc.getName()+"的人口数据");
//                                 }
//                                 Map<String,BigDecimal> popMap = buildGridMap(popoluationList,casualtiesDE.getHouseData(),pcc,null);
//                                 if(popMap.values().size()==0){
//                                     throw new RuntimeException("计算失败，无法根据人口数据匹配到房屋单体数据");
//                                 }
//                                 for (SettingInfluenceFliedEntity earthquakeAffected : influenceList) {
//                                     //当前省市县的易损性数据
//                                     Table<String, String, List<BuildingVulnerability>> ysxTable =  handleYsxData(pcc);
//                                     //获取在该影响场数据中的所有的房屋单体数据
//                                     List<BuildingIndividualEntity> buildingList = buildingIndividualRepository.getAllWithGeom(casualtiesDE.getHouseData(),earthquakeAffected.getGeom(),pcc.getPpName(),pcc.getCityName(),pcc.getName());
//                                     if(PlatformObjectUtils.isNotEmpty(buildingList) && buildingList.size()>0){
//                                         publicOperateSave(version, casualtiesDE, map, popMap, calculationList, buildingList,ysxTable,pcc,null);
//                                     }
//                                 }
//                             }
//                         }
//                     }
//                 }
//                 if(calculationList.size()>0){
//                     casualtiesDERepository.batchSaveCasualtyResult(calculationList);
//                 }
//             }else{
//                 //获取房屋单体数据
//                 List<BuildingIndividualEntity> buildingIndividualEntityList = centerEvaluate2( casualtiesDE, version);
//                 //根据字典值获取不同结构类型的具体数据并计算
//                 Map<String,Table<String, String, List<BuildingVulnerability>>> bmap = new HashMap<>();
//                 //存取所有的网格信息结果用于保存
//                 List<CasualtiesResult> calculationList = new ArrayList<>();
//                 //存放的是人口网格信息
//                 List<LinkedHashMap> popoluationList = new ArrayList<>();
//                 //存放的是四个概率水准的数据
//                 List<ProbabilityLevel> probabilityLevelList= new ArrayList<>();
//                 Map<String, List<ProbabilityLevel>> proMap = new HashMap<>();
//                 Map<String,BigDecimal> popMap = new HashMap<>();
//                 if (PlatformObjectUtils.isNotEmpty(buildingIndividualEntityList) && buildingIndividualEntityList.size() > 0) {
//                     List<String> districts = buildingIndividualEntityList.stream().map(buildingIndividualEntity -> buildingIndividualEntity.getProvince() + "-" + buildingIndividualEntity.getCity() + "-" + buildingIndividualEntity.getCounty()).distinct().collect(Collectors.toList());
//                     if(PlatformObjectUtils.isNotEmpty(districts) && districts.size()>0){
//                         for (String district : districts) {
//                             PCC pcc = new PCC();
//                             pcc.setPpName(district.split("-")[0]);
//                             pcc.setCityName(district.split("-")[1]);
//                             pcc.setName(district.split("-")[2]);
//                             //获取区县的人口格网数据
//                             List<LinkedHashMap> popList = getPopoluationList(casualtiesDE.getPopluationVersion(),pcc);
// //                            if(PlatformObjectUtils.isEmpty(popoluationList) || popoluationList.size()==0){
// //                                throw new RuntimeException("计算失败，人口格网版本为"+casualtiesDE.getPopluationVersion()+"下获取不到"+pcc.getPpName()+"-"+pcc.getCityName()+"_"+pcc.getName()+"的人口数据");
// //                            }
//                             buildGridMap(popList,casualtiesDE.getHouseData(),pcc,popMap);
//                             if(popMap.values().size()==0){
//                                 throw new RuntimeException("计算失败，无法根据人口数据匹配到房屋单体数据");
//                             }
//                         }
//                     }
//                     for (BuildingIndividualEntity obj : buildingIndividualEntityList) {
//                         //四个概率水准实体
//                         ProbabilityLevel probabilityLevel = null;
//                         if (PlatformObjectUtils.isEmpty(obj.getProvince())||PlatformObjectUtils.isEmpty(obj.getCity())||PlatformObjectUtils.isEmpty(obj.getCounty())){
//                             continue;
//                         }
//                         Table<String, String, List<BuildingVulnerability>> ysxTable = null;
//                         //根据网格的省市县查询数据
//                         if(!bmap.containsKey(obj.getProvince()+"-"+obj.getCity()+"-"+obj.getCounty())){
//                             PCC pcc = new PCC();
//                             pcc.setPpName(obj.getProvince());
//                             pcc.setCityName(obj.getCity());
//                             pcc.setName(obj.getCounty());
//                             //查询易损性数据
//                             ysxTable =  handleYsxData(pcc);
//                             bmap.put(obj.getProvince()+"-"+obj.getCity()+"-"+obj.getCounty(),ysxTable);
//                             if("1".equals(casualtiesDE.getSeismicInputMode())){
//                                 //表示是四个概率水准
//                                 List<ProbabilityLevel> intensityList = null;
//                                 if(!proMap.containsKey(pcc.getPpName()+"-"+pcc.getCityName()+"-"+pcc.getName())){
//                                     intensityList = getLdAndPgaData(version, type, pcc);
//                                     proMap.put(pcc.getPpName()+"-"+pcc.getCityName()+"-"+pcc.getName(),intensityList);
//                                 }else{
//                                     intensityList = proMap.get(pcc.getPpName()+"-"+pcc.getCityName()+"-"+pcc.getName());
//                                 }
//                                 if(PlatformObjectUtils.isEmpty(intensityList) || intensityList.size()==0){
//                                     throw new RuntimeException("计算失败，版本为"+version+"下获取不到"+pcc.getPpName()+"-"+pcc.getCityName()+"_"+pcc.getName()+"的四个概率水准数据");
//                                 }
//
//                                 for(ProbabilityLevel e:intensityList){
//                                     if (economicLossEDRepository.getSTIntersects(e.getGeom(), BigDecimal.valueOf(obj.getLongitude()),
//                                             BigDecimal.valueOf(obj.getLatitude()))) {
//                                         probabilityLevel = e;
//                                         break;
//                                     }
//                                 }
//                                 if (probabilityLevel == null) {
//                                     continue;
//                                 }
//                             }
//
//                         }else{
//                             ysxTable =  bmap.get(obj.getProvince()+"-"+obj.getCity()+"-"+obj.getCounty());
//                             List<ProbabilityLevel> intensityList = proMap.get(obj.getProvince()+"-"+obj.getCity()+"-"+obj.getCounty());
//                             for(ProbabilityLevel e:intensityList){
//                                 if (economicLossEDRepository.getSTIntersects(e.getGeom(), BigDecimal.valueOf(obj.getLongitude()),
//                                         BigDecimal.valueOf(obj.getLatitude()))) {
//                                     probabilityLevel = e;
//                                     break;
//                                 }
//                             }
//                         }
//                         SettingInfluenceFliedEntity earthquakeAffected = null;
//                         if("1".equals(casualtiesDE.getSeismicInputMode())){
//                             earthquakeAffected = new SettingInfluenceFliedEntity();
//                             //四个概率
//                             earthquakeAffected.setDzIntensity(getPgaIntensity(probabilityLevel, type));
//                             String pga = "sgglsz1";
//                             earthquakeAffected.setId(pga);
//                         }else if("2".equals(casualtiesDE.getSeismicInputMode())){
//                             //影响场  obj已经确定影响场的烈度 所以直接计算对应烈度的即可
//                             earthquakeAffected = new SettingInfluenceFliedEntity();
//                             earthquakeAffected.setDzIntensity(obj.getIntensity());
//                         }
//                         publicOperateSave1(version, casualtiesDE, map, popMap, calculationList, obj,ysxTable,earthquakeAffected);
//                     }
//                 }
//                 if(calculationList.size()>0){
//                     casualtiesDERepository.batchSaveCasualtyResult(calculationList);
//                 }
//             }
//             boolean bool = hypergraphService.getWorkspaceReload("fxqh_casualties_calculation_ed");
//         }
//     }

    private void publicOperateSave1(String version, CalculationTasks calculationTasks, Map<Object, Object> map, Map<String, BigDecimal> popMap, List<CasualtiesResult> calculationList
            , BuildingIndividualEntity buildingIndividualEntity, Map<String, Map<String, Map<String, BuildingVulnerability>>> ysxTable
            , SettingInfluenceFliedEntity earthquakeAffected, String seismicInputMode) {
        String structureType1 = PlatformObjectUtils.isEmpty(map.get(buildingIndividualEntity.getStructureType1())) ? "" : map.get(buildingIndividualEntity.getStructureType1()).toString();
        String structureType2 = PlatformObjectUtils.isEmpty(map.get(buildingIndividualEntity.getStructureType2())) ? "" : map.get(buildingIndividualEntity.getStructureType2()).toString();
        String defenceLevel = sfIntensityMap().get(buildingIndividualEntity.getDefenceLevel());
        //房屋内人员的密度 =（一个网格中的人口/网格中所有单体的面积）*当前单体的面积
        BigDecimal divide = popMap.get(buildingIndividualEntity.getBuildingCode());
        //三类房屋用途在不同设防烈度下的面积
        BigDecimal area = org.apache.commons.lang3.StringUtils.isBlank(buildingIndividualEntity.getArea()) ? BigDecimal.ZERO : new BigDecimal(buildingIndividualEntity.getArea());
        //房屋内人员的密度
        BigDecimal density = (PlatformObjectUtils.isNotEmpty(divide) ? divide : BigDecimal.ZERO).multiply(area);
        //获取易损性建筑物类型、指定设防烈度的易损性数据
        String structureType = structureType1 + (PlatformObjectUtils.isNotEmpty(structureType2) ? "-" + structureType2 : "");
        Map<String, Map<String, BuildingVulnerability>> stringListMap = ysxTable.get(structureType);
        Map<String, BuildingVulnerability> vulnerabilityList = stringListMap.get(defenceLevel);
        if (stringListMap == null || stringListMap.size() < 1) {
            return;
        }
        //构建地震烈度数据
        List<Integer> dzIntensityList = getDzIntensityList(earthquakeAffected, seismicInputMode,earthquakeAffected.getId());
        //6-10表示真实的地震烈度
        int num = 1;
        for (Integer i : dzIntensityList) {
            //烈度為5不计算
            if (i == 5) {
                num++;
                continue;
            }
            CasualtiesResult casualtiesResult = new CasualtiesResult();
            //每个地震烈度下不同建筑物类型白天死亡、重伤人数；夜晚死亡、重伤人数
            BigDecimal nightTotalDeathNum = BigDecimal.ZERO;
            BigDecimal nightTotalInjureNum = BigDecimal.ZERO;
            BigDecimal dayTotalDeathNum = BigDecimal.ZERO;
            BigDecimal dayTotalInjureNum = BigDecimal.ZERO;
            if (vulnerabilityList != null && vulnerabilityList.size() > 0) {
                //不同结构类型中的三类结构在不同设防烈度下、地震烈度为6-10度下的人员死亡和重伤人数
                Map<String, BigDecimal> resultMap = getCasualtiesValue(area, vulnerabilityList, i, buildingIndividualEntity.getUsage1(), density);
                //resultMap是不同结构类型的房屋网格在每个地震烈度下的各个设防烈度下的人员死亡和人员重伤
                BigDecimal nd = resultMap.get("nd");
                //夜间人员死亡
                nightTotalDeathNum = nightTotalDeathNum.add(nd);
                BigDecimal ni = resultMap.get("ni");
                //夜间人员重伤
                nightTotalInjureNum = nightTotalInjureNum.add(ni);
                BigDecimal dd = resultMap.get("dd");
                //白天人员死亡
                dayTotalDeathNum = dayTotalDeathNum.add(dd);
                BigDecimal di = resultMap.get("di");
                //白天人员重伤
                dayTotalInjureNum = dayTotalInjureNum.add(di);
            }
            casualtiesResult.setId(UUIDGenerator.getUUID());
            casualtiesResult.setAssessId(calculationTasks.getId());
            casualtiesResult.setAssessCode(calculationTasks.getAssessCode());
            casualtiesResult.setProvinceName(buildingIndividualEntity.getProvince());
            casualtiesResult.setCityName(buildingIndividualEntity.getCity());
            casualtiesResult.setCountyName(buildingIndividualEntity.getCounty());
            casualtiesResult.setGeographyId(buildingIndividualEntity.getBuildingCode());
            casualtiesResult.setDayDeath(dayTotalDeathNum);
            casualtiesResult.setDayDeathCorrectionValue(dayTotalDeathNum);
            casualtiesResult.setNightDeath(nightTotalDeathNum);
            casualtiesResult.setNightDeathCorrectionValue(nightTotalDeathNum);
            casualtiesResult.setDayInjure(dayTotalInjureNum);
            casualtiesResult.setDayInjureCorrectionValue(dayTotalInjureNum);
            casualtiesResult.setNightInjure(nightTotalInjureNum);
            casualtiesResult.setNightInjureCorrectionValue(nightTotalInjureNum);
            if (earthquakeAffected != null) {
                String fsiId = earthquakeAffected.getId();
//                if ("1".equals(seismicInputMode)) {
//                    fsiId = fsiId.substring(0, fsiId.length() - 1);
//                    fsiId = fsiId + "" + num;
//                }
                casualtiesResult.setCondition(org.apache.commons.lang3.StringUtils.isNotBlank(fsiId) ? fsiId : version);
                casualtiesResult.setIntensity(intensityMap().get(i));
            } else {
                casualtiesResult.setCondition("");
                casualtiesResult.setIntensity(intensityMap().get(i));
            }
            casualtiesResult.setStructure(structureType1 + "-" + structureType2);
            casualtiesResult.setGeom("POINT(" + buildingIndividualEntity.getLongitude() + " " + buildingIndividualEntity.getLatitude() + ")");
            casualtiesResult.setTotalArea(area);
            casualtiesResult.setCreateUser(PlatformSessionContext.getUserID());
            casualtiesResult.setCreateTime(new Date());
            casualtiesResult.setDelFlag("0");
            casualtiesResult.setVersion(PlatformObjectUtils.isNotEmpty(version) ? version : "");
            casualtiesResult.setExtends1("");
            casualtiesResult.setFlag(seismicInputMode);
            calculationList.add(casualtiesResult);
            num++;
        }
    }


    private List<BuildingIndividualEntity> centerEvaluate2(CalculationTasks calculationTasks, String version, String seismicInputMode) {
        //数据视图条件
        QueryByVersionParam queryByVersionParam = new QueryByVersionParam();
        //写入条件版本号
        queryByVersionParam.setVersionCode(calculationTasks.getHouseData());
//                    //0为省市区县1为地图圈选
        queryByVersionParam.setGeomType(1);
        queryByVersionParam.setGeom(calculationTasks.getCoordinateRange());
        if ("2".equals(seismicInputMode)) {
            queryByVersionParam.setInfluenceVersion(version);
        }
        List<BuildingIndividualEntity> jggwList = null;
        if ("2".equals(seismicInputMode)) {
            jggwList = buildingIndividualRepository.queryDataByParam1(queryByVersionParam);
        } else {
            jggwList = buildingIndividualRepository.queryYwData(queryByVersionParam);
        }
        return jggwList;
    }

    private void handleProbabilityLevelData(List<CasualtiesResult> finalResultList, List<LinkedHashMap> popoluationList) {
        //人员按相同房屋网格id分组<相同房屋网格id,List<LinkedHashMap>>
        Map<String, List<LinkedHashMap>> linkedMap = popoluationList.stream().collect(Collectors.groupingBy(linkedHashMap -> (String) linkedHashMap.get("extends1")));
        Map<String, List<CasualtiesResult>> collect1 = finalResultList.stream().collect(Collectors.groupingBy(CasualtiesResult::getExtends1));
        //不同地震烈度下13张表中同属一个房屋格网的数据
        collect1.forEach((k1, v1) -> {
            //13张表中同属于一个房屋网格的13条数据面积之和 才是这个完整网格的面积
            BigDecimal totalArea = v1.stream()
                    .map(CasualtiesResult::getTotalArea)
                    .reduce(BigDecimal.ZERO, BigDecimal::add).setScale(6, RoundingMode.DOWN);
            CasualtiesResult casualtiesResult = v1.get(0);
            List<LinkedHashMap> linkedHashMaps = linkedMap.get(k1);
            BigDecimal m = BigDecimal.ZERO;
            if (PlatformObjectUtils.isNotEmpty(linkedHashMaps) && linkedHashMaps.size() > 0) {
                LinkedHashMap linkedHashMap = linkedHashMaps.get(0);
                //格网总人口
                BigDecimal personNum = new BigDecimal(linkedHashMap.get("tzl3").toString());
                if (totalArea.compareTo(BigDecimal.ZERO) > 0) {
                    m = personNum.divide(totalArea, 6, RoundingMode.HALF_DOWN);
                }
            }
//                else {
//                    throw new RuntimeException("评估失败,获取不到id为" + casualtiesResult.getGeographyId() + "的人口数据");
//                }
            //获取13张表同属于一个网格的死亡和重伤人数的总和
            BigDecimal nightDeath = v1.stream()
                    .map(CasualtiesResult::getNightDeath)
                    .reduce(BigDecimal.ZERO, BigDecimal::add).setScale(6, RoundingMode.DOWN);
            casualtiesResult.setNightDeath(nightDeath.multiply(m));
            casualtiesResult.setNightDeathCorrectionValue(nightDeath.multiply(m));
            BigDecimal nightInjure = v1.stream()
                    .map(CasualtiesResult::getNightInjure)
                    .reduce(BigDecimal.ZERO, BigDecimal::add).setScale(6, RoundingMode.DOWN);
            casualtiesResult.setNightInjure(nightInjure.multiply(m));
            casualtiesResult.setNightInjureCorrectionValue(nightInjure.multiply(m));
            BigDecimal dayDeath = v1.stream()
                    .map(CasualtiesResult::getDayDeath)
                    .reduce(BigDecimal.ZERO, BigDecimal::add).setScale(6, RoundingMode.DOWN);
            casualtiesResult.setDayDeath(dayDeath.multiply(m));
            casualtiesResult.setDayDeathCorrectionValue(dayDeath.multiply(m));
            BigDecimal dayInjure = v1.stream()
                    .map(CasualtiesResult::getDayInjure)
                    .reduce(BigDecimal.ZERO, BigDecimal::add).setScale(6, RoundingMode.DOWN);
            casualtiesResult.setDayInjure(dayInjure.multiply(m));
            casualtiesResult.setDayInjureCorrectionValue(dayInjure.multiply(m));
            casualtiesResult.setTotalArea(totalArea);
            //casualtiesResult.setFlag(flag);
            finalResultList.add(casualtiesResult);
        });

    }

    private List<CasualtiesResult> getYwData1(Grid13VO obj, Map<String, Map<String, Map<String, BuildingVulnerability>>> ysxTable, CalculationTasks calculationTasks
            , SettingInfluenceFliedEntity earthquakeAffected, String version, List<StructureHouseUsingPercent> percentList
            , String seismicInputMode) throws StrategyFactoryException, BizException {
        List<CasualtiesResult> calculationTotalList = new ArrayList<>();
        //一个obj就是一个网格
        //总面积当前坐标总面积
        Double totalArea = obj.getTotalArea();
        //住宅房屋面积（第Ⅰ类）
        BigDecimal residence = (obj.getResidence() == 0.0 ? BigDecimal.ZERO : (BigDecimal.valueOf(obj.getResidence()).divide(BigDecimal.valueOf(100), 6, RoundingMode.HALF_DOWN)));
        //办公房屋面积（第Ⅱ类）
        BigDecimal office = (obj.getOffice() == 0.0 ? BigDecimal.ZERO : (BigDecimal.valueOf(obj.getOffice()).divide(BigDecimal.valueOf(100), 6, RoundingMode.HALF_DOWN)));
        //商业房屋面积（第Ⅲ类）
        BigDecimal business = (obj.getBusiness() == 0.0 ? BigDecimal.ZERO : (BigDecimal.valueOf(obj.getBusiness()).divide(BigDecimal.valueOf(100), 6, RoundingMode.HALF_DOWN)));
        //医疗教育面积（第Ⅲ类）
        BigDecimal medic = (obj.getMedic() == 0.0 ? BigDecimal.ZERO : (BigDecimal.valueOf(obj.getMedic()).divide(BigDecimal.valueOf(100), 6, RoundingMode.HALF_DOWN)));
        //其他房屋面积（第Ⅲ类）
        BigDecimal other = (obj.getOther() == 0.0 ? BigDecimal.ZERO : (BigDecimal.valueOf(obj.getOther()).divide(BigDecimal.valueOf(100), 6, RoundingMode.HALF_DOWN)));
        if (residence.compareTo(BigDecimal.ZERO) == 0 && office.compareTo(BigDecimal.ZERO) == 0 && business.compareTo(BigDecimal.ZERO) == 0
                && medic.compareTo(BigDecimal.ZERO) == 0 && other.compareTo(BigDecimal.ZERO) == 0) {
            //格网面积有但是各个房屋用途均为0需要使用数据库中存储的各房屋用途备用比例
            Map<String, List<StructureHouseUsingPercent>> collect = percentList.stream().collect(Collectors.groupingBy(StructureHouseUsingPercent::getStructure));
            StructureHouseUsingPercent structureHouseUsingPercent = collect.get(obj.getStructureType()).get(0);
            residence = structureHouseUsingPercent.getResidence();
            office = structureHouseUsingPercent.getOffice();
            business = structureHouseUsingPercent.getBusiness();
            medic = structureHouseUsingPercent.getMedic();
            other = structureHouseUsingPercent.getOther();
        }
        BigDecimal residenceArea = residence.multiply(BigDecimal.valueOf(totalArea));
        BigDecimal officeArea = office.multiply(BigDecimal.valueOf(totalArea));
        BigDecimal businessArea = business.multiply(BigDecimal.valueOf(totalArea));
        BigDecimal medicArea = medic.multiply(BigDecimal.valueOf(totalArea));
        BigDecimal otherArea = other.multiply(BigDecimal.valueOf(totalArea));

        // //map <建筑结构,<设防烈度,建筑物易损性的结合>>
        // Map<String, Map<String, List<BuildingVulnerability>>> map = ysxTable.rowMap();
        String mapKey = "";
        //获取对应易损性结构类型
        if (!"城镇钢混结构".equals(obj.getStructureType())) {
            mapKey = (String) buildStructureTable().get(obj.getStructureType(), obj.getStructureType());
        } else {
            //城镇钢混结构需要根据建筑的楼层确定易损性结构类型
            if ((obj.getF1() + obj.getF2F3() + obj.getF4F6() + obj.getF7F10() + obj.getF11F16() + obj.getF17F30() + obj.getF31()) == 0) {
                //实际数据中有的数据层数占比全是0，无层数百分比，结构类型对应时，城镇钢混结构对应到钢筋混凝土结构-框架结构
                mapKey = (String) buildStructureTable().get(obj.getStructureType(), "8");
            } else {
                if (obj.getF31() > 0 || obj.getF17F30() > 0) {
                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "19");
                } else if (obj.getF7F10() > 0 || obj.getF11F16() > 0) {
                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "18");
                } else {
                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "8");
                }
            }
            if ("剪力墙结构".equals(mapKey)) {
                mapKey = "钢筋混凝土结构-" + mapKey;
            }
        }
        //组建13张表数据中烈度和对应的烈度面积占比结构
        Map<String, BigDecimal> intensitAreaMap = getIntensitArea(obj);
        //<设防烈度,建筑物易损性的结合>
        Map<String, Map<String, BuildingVulnerability>> sfIntensityMap = ysxTable.get(mapKey);
        //每种结构所具备的设防烈度
        List<String> intensityList = getIntensityList(obj);
        List<CasualtiesResult> calculationList = new ArrayList<>();
        //设置地震烈度
        List<Integer> dzIntensityList = getDzIntensityList(earthquakeAffected, seismicInputMode,earthquakeAffected.getId());
        if (intensityList.size() > 0) {
            //6-10表示真实的地震烈度
            int num = 1;
            for (Integer i : dzIntensityList) {
                CasualtiesResult casualtiesResult = new CasualtiesResult();
                //每个地震烈度下不同建筑物类型白天死亡、重伤人数；夜晚死亡、重伤人数
                BigDecimal nightTotalDeathNum = BigDecimal.ZERO;
                BigDecimal nightTotalInjureNum = BigDecimal.ZERO;
                BigDecimal dayTotalDeathNum = BigDecimal.ZERO;
                BigDecimal dayTotalInjureNum = BigDecimal.ZERO;
                if (sfIntensityMap != null && sfIntensityMap.size() > 0) {
                    //每种结构所具备的设防烈度（未设防-9度）
                    for (String intensity : intensityList) {
                        //易损性数据下设防烈度对应的数据
                        Map<String, BuildingVulnerability> vulnerabilityList =  sfIntensityMap.get(intensity);
                        if(PlatformObjectUtils.isEmpty(vulnerabilityList) || vulnerabilityList.size()==0){
                            throw new RuntimeException("计算未完成，无法获取"+mapKey+"下设防情况为"+intensity+"的易损性数据");
                        }
                        BuildingVulnerability buildingVulnerability = vulnerabilityList.get(intensity + "");
                        if(PlatformObjectUtils.isEmpty(buildingVulnerability)){
                            throw new RuntimeException("计算未完成，无法获取"+mapKey+"下设防情况为"+intensity+"烈度为"+i+"度的易损性数据”");
                        }
                        //不同设防烈度房屋面积占比
                        BigDecimal ratio = intensitAreaMap.get(intensity).divide(BigDecimal.valueOf(100), 4, RoundingMode.HALF_DOWN);
                        //三类房屋用途在不同设防烈度下的面积
                        BigDecimal residenceRatioArea = residenceArea.multiply(ratio);
                        BigDecimal officeRatioArea = officeArea.multiply(ratio);
                        BigDecimal businessRatioArea = businessArea.multiply(ratio);
                        BigDecimal medicRatioArea = medicArea.multiply(ratio);
                        BigDecimal otherRatioArea = otherArea.multiply(ratio);
                        //不同结构类型中的三类结构在不同设防烈度下、地震烈度为6-10度下的人员死亡和重伤人数
                        Map<String, BigDecimal> resultMap = getCasualtiesValue(residenceRatioArea, officeRatioArea, businessRatioArea, medicRatioArea, otherRatioArea, vulnerabilityList, i);
                        //resultMap是不同结构类型的房屋网格在每个地震烈度下的各个设防烈度下的人员死亡和人员重伤
                        BigDecimal nd = resultMap.get("nd");
                        //夜间人员死亡
                        nightTotalDeathNum = nightTotalDeathNum.add(nd);
                        BigDecimal ni = resultMap.get("ni");
                        //夜间人员重伤
                        nightTotalInjureNum = nightTotalInjureNum.add(ni);
                        BigDecimal dd = resultMap.get("dd");
                        //白天人员死亡
                        dayTotalDeathNum = dayTotalDeathNum.add(dd);
                        BigDecimal di = resultMap.get("di");
                        //白天人员重伤
                        dayTotalInjureNum = dayTotalInjureNum.add(di);

                    }
                }
                casualtiesResult.setId(UUIDGenerator.getUUID());
                casualtiesResult.setAssessId(calculationTasks.getId());
                casualtiesResult.setAssessCode(calculationTasks.getAssessCode());
                casualtiesResult.setProvinceName(obj.getProvince());
                casualtiesResult.setCityName(obj.getCity());
                casualtiesResult.setCountyName(obj.getCounty());
                casualtiesResult.setGeographyId(obj.getId());
                casualtiesResult.setDayDeath(dayTotalDeathNum);
                casualtiesResult.setDayDeathCorrectionValue(dayTotalDeathNum);
                casualtiesResult.setNightDeath(nightTotalDeathNum);
                casualtiesResult.setNightDeathCorrectionValue(nightTotalDeathNum);
                casualtiesResult.setDayInjure(dayTotalInjureNum);
                casualtiesResult.setDayInjureCorrectionValue(dayTotalInjureNum);
                casualtiesResult.setNightInjure(nightTotalInjureNum);
                casualtiesResult.setNightInjureCorrectionValue(nightTotalInjureNum);
                //如果是地震影响场condition存的是影响场iD，如果是烈度，condition存的是烈度，如果是四个概率水准，则存的是四个概率水准对应的数据
                if (earthquakeAffected != null) {
                    String fsiId = earthquakeAffected.getId();
                    if (org.apache.commons.lang3.StringUtils.isBlank(fsiId)) {
                        fsiId = seismicImpactFieldRepository.getInfluencefliedId(version, earthquakeAffected.getDzIntensity());
                    }
                    if ("1".equals(seismicInputMode)) {
                        fsiId = fsiId.substring(0, fsiId.length() - 1);
                        fsiId = fsiId + "" + num;
                    }
                    casualtiesResult.setCondition(org.apache.commons.lang3.StringUtils.isNotBlank(fsiId) ? fsiId : version);
                    casualtiesResult.setIntensity(intensityMap().get(i));
                } else {
                    casualtiesResult.setCondition("");
                    casualtiesResult.setIntensity(intensityMap().get(i));
                }
                casualtiesResult.setStructure(obj.getStructureType());
                casualtiesResult.setGeom(obj.getGeom());
                casualtiesResult.setTotalArea(obj.getTotalArea() == null || obj.getTotalArea() == 0 ? BigDecimal.ZERO : BigDecimal.valueOf(obj.getTotalArea()));
                casualtiesResult.setCreateUser(PlatformSessionContext.getUserID());
                casualtiesResult.setCreateTime(new Date());
                casualtiesResult.setDelFlag("0");
                casualtiesResult.setVersion(version);
                casualtiesResult.setExtends1(obj.getExtends1());
                casualtiesResult.setFlag(seismicInputMode);
                calculationList.add(casualtiesResult);
                num++;
            }
        }
        calculationTotalList.addAll(calculationList);

        return calculationTotalList;
    }

    private void publicOperateSave(String version, CalculationTasks calculationTasks, Map<Object, Object> map, Map<String, BigDecimal> popMap
            , List<CasualtiesResult> calculationList, List<BuildingIndividualEntity> buildingIndividualEntities
            , Map<String, Map<String, Map<String, BuildingVulnerability>>> ysxTable, PCC pcc, SettingInfluenceFliedEntity earthquakeAffected
            , String seismicInputMode) throws Exception {
        for (BuildingIndividualEntity buildingIndividualEntity : buildingIndividualEntities) {
            String structureType1 = PlatformObjectUtils.isEmpty(map.get(buildingIndividualEntity.getStructureType1())) ? "" : map.get(buildingIndividualEntity.getStructureType1()).toString();
            String structureType2 = PlatformObjectUtils.isEmpty(map.get(buildingIndividualEntity.getStructureType2())) ? "" : map.get(buildingIndividualEntity.getStructureType2()).toString();
            String defenceLevel = sfIntensityMap().get(buildingIndividualEntity.getDefenceLevel());
            //房屋内人员的密度 =（一个网格中的人口/网格中所有单体的面积）*当前单体的面积
            BigDecimal divide = popMap.get(buildingIndividualEntity.getBuildingCode());
            //三类房屋用途在不同设防烈度下的面积
            BigDecimal area = org.apache.commons.lang3.StringUtils.isBlank(buildingIndividualEntity.getArea()) ? BigDecimal.ZERO : new BigDecimal(buildingIndividualEntity.getArea());
            //房屋内人员的密度
            BigDecimal density = (PlatformObjectUtils.isNotEmpty(divide) ? divide : BigDecimal.ZERO).multiply(area);
            //获取易损性建筑物类型、指定设防烈度的易损性数据
            String structureType = structureType1 + (PlatformObjectUtils.isNotEmpty(structureType2) ? "-" + structureType2 : "");
            Map<String, Map<String, BuildingVulnerability>> stringListMap = ysxTable.get(structureType);
            if (stringListMap == null || stringListMap.size() < 1) {
                continue;
            }
            Map<String, BuildingVulnerability> vulnerabilityList = stringListMap.get(defenceLevel);
            //构建地震烈度数据
            List<Integer> dzIntensityList = getDzIntensityList(earthquakeAffected, seismicInputMode,earthquakeAffected.getId());
            //6-10表示真实的地震烈度
            int num = 1;
            for (Integer i : dzIntensityList) {
                //烈度為5不计算
                if (i == 5) {
                    num++;
                    continue;
                }
                CasualtiesResult casualtiesResult = new CasualtiesResult();
                //每个地震烈度下不同建筑物类型白天死亡、重伤人数；夜晚死亡、重伤人数
                BigDecimal nightTotalDeathNum = BigDecimal.ZERO;
                BigDecimal nightTotalInjureNum = BigDecimal.ZERO;
                BigDecimal dayTotalDeathNum = BigDecimal.ZERO;
                BigDecimal dayTotalInjureNum = BigDecimal.ZERO;
                if (vulnerabilityList != null && vulnerabilityList.size() > 0) {
                    //不同结构类型中的三类结构在不同设防烈度下、地震烈度为6-10度下的人员死亡和重伤人数
                    Map<String, BigDecimal> resultMap = getCasualtiesValue(area, vulnerabilityList, i, buildingIndividualEntity.getUsage1(), density);
                    //resultMap是不同结构类型的房屋网格在每个地震烈度下的各个设防烈度下的人员死亡和人员重伤
                    BigDecimal nd = resultMap.get("nd");
                    //夜间人员死亡
                    nightTotalDeathNum = nightTotalDeathNum.add(nd);
                    BigDecimal ni = resultMap.get("ni");
                    //夜间人员重伤
                    nightTotalInjureNum = nightTotalInjureNum.add(ni);
                    BigDecimal dd = resultMap.get("dd");
                    //白天人员死亡
                    dayTotalDeathNum = dayTotalDeathNum.add(dd);
                    BigDecimal di = resultMap.get("di");
                    //白天人员重伤
                    dayTotalInjureNum = dayTotalInjureNum.add(di);
                }
                casualtiesResult.setId(UUIDGenerator.getUUID());
                casualtiesResult.setAssessId(calculationTasks.getId());
                casualtiesResult.setAssessCode(calculationTasks.getAssessCode());
                casualtiesResult.setProvinceName(pcc.getPpName());
                casualtiesResult.setCityName(pcc.getCityName());
                casualtiesResult.setCountyName(pcc.getName());
                casualtiesResult.setGeographyId(buildingIndividualEntity.getBuildingCode());
                casualtiesResult.setDayDeath(dayTotalDeathNum);
                casualtiesResult.setDayDeathCorrectionValue(dayTotalDeathNum);
                casualtiesResult.setNightDeath(nightTotalDeathNum);
                casualtiesResult.setNightDeathCorrectionValue(nightTotalDeathNum);
                casualtiesResult.setDayInjure(dayTotalInjureNum);
                casualtiesResult.setDayInjureCorrectionValue(dayTotalInjureNum);
                casualtiesResult.setNightInjure(nightTotalInjureNum);
                casualtiesResult.setNightInjureCorrectionValue(nightTotalInjureNum);
                if (earthquakeAffected != null) {
                    String fsiId = earthquakeAffected.getId();
                    if ("1".equals(seismicInputMode)) {
                        fsiId = fsiId.substring(0, fsiId.length() - 1);
                        fsiId = fsiId + "" + num;
                    }
                    casualtiesResult.setCondition(org.apache.commons.lang3.StringUtils.isNotBlank(fsiId) ? fsiId : version);
                    casualtiesResult.setIntensity(intensityMap().get(i));
                } else {
                    casualtiesResult.setCondition("");
                    casualtiesResult.setIntensity(intensityMap().get(i));
                }
                casualtiesResult.setStructure(structureType1 + "-" + structureType2);
                casualtiesResult.setGeom("POINT(" + buildingIndividualEntity.getLongitude() + " " + buildingIndividualEntity.getLatitude() + ")");
                casualtiesResult.setTotalArea(area);
                casualtiesResult.setCreateUser(PlatformSessionContext.getUserID());
                casualtiesResult.setCreateTime(new Date());
                casualtiesResult.setDelFlag("0");
                casualtiesResult.setVersion(PlatformObjectUtils.isNotEmpty(version) ? version : "");
                casualtiesResult.setExtends1("");
                casualtiesResult.setFlag(seismicInputMode);
                calculationList.add(casualtiesResult);
                num++;
            }
        }

    }


    private List<ProbabilityLevel> getLdAndPgaData(String version, String type, PCC pcc) throws BizException {
        List<ProbabilityLevel> intensityList = new ArrayList<>();
        if ("0".equals(type)) {
            //烈度
            List<JcLd> data = jcsjRestManager.getLDList(pcc.getPpName(), pcc.getCityName(), pcc.getName(), version).getData();
            if (data != null) {
                for (JcLd datum : data) {
                    ProbabilityLevel probabilityLevel = new ProbabilityLevel();
                    BeanUtils.copyProperties(datum, probabilityLevel);
                    probabilityLevel.setPga50year63(datum.getLd50year63());
                    probabilityLevel.setPga50year10(datum.getLd50year10());
                    probabilityLevel.setPga50year2(datum.getLd50year2());
                    probabilityLevel.setPga100year1(datum.getLd100year1());
                    intensityList.add(probabilityLevel);
                }
            }
        } else if ("1".equals(type)) {
            //pga数据
            List<JcPga> pgaData = jcsjRestManager.getPagList(pcc.getPpName(), pcc.getCityName(), pcc.getName(), version).getData();
            if (pgaData != null) {
                for (JcPga datum : pgaData) {
                    ProbabilityLevel probabilityLevel = new ProbabilityLevel();
                    BeanUtils.copyProperties(datum, probabilityLevel);
                    probabilityLevel.setPga50year63(datum.getPga50year63()+"");
                    probabilityLevel.setPga50year10(datum.getPga50year10()+"");
                    probabilityLevel.setPga50year2(datum.getPga50year2()+"");
                    probabilityLevel.setPga100year1(datum.getPga100year1()+"");
                    intensityList.add(probabilityLevel);
                }
            }
        }
        return intensityList;
    }

    //求房屋单体房屋内人员的密度过程的中间结果-》一个网格中的人口/网格中所有单体的面积
    private Map<String, BigDecimal> buildGridMap(List<LinkedHashMap> popoluationList, String version, PCC pcc, Map<String, BigDecimal> popMap) {
        if (popMap == null) {
            popMap = new HashMap<>();
        }
        for (LinkedHashMap linkedHashMap : popoluationList) {
            String geom = linkedHashMap.get("geom").toString();
            //获取人口格网中所有的房屋单体
            List<PopulationBuildingIndividualVO> vos = buildingIndividualRepository.getAllWithGeomAndArea(geom, version, pcc.getPpName(), pcc.getCityName(), pcc.getName());
            Object obj = linkedHashMap.get("tzl3");
            BigDecimal divide = BigDecimal.ZERO;
            if (PlatformObjectUtils.isNotEmpty(obj)) {
                BigDecimal totalPopulation = new BigDecimal(obj.toString());
                if (PlatformObjectUtils.isNotEmpty(vos) && vos.size() > 0) {
                    BigDecimal totalArea = vos.stream().filter(populationBuildingIndividualVO -> PlatformObjectUtils.isNotEmpty(populationBuildingIndividualVO.getArea()))
                            .map(PopulationBuildingIndividualVO::getArea)
                            // 使用reduce()聚合函数,实现累加器
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    divide = totalPopulation.divide(totalArea, 6, RoundingMode.HALF_DOWN);
                }
            }
            for (PopulationBuildingIndividualVO vo : vos) {
                popMap.put(vo.getBuildingCode(), divide);
            }
        }
        return popMap;
    }

    private Map<String, String> sfIntensityMap() {
        Map<String, String> map = new HashMap<>();
        map.put("0", "未设防");
        map.put("6", "6度");
        map.put("7", "7度");
        map.put("8", "8度");
        map.put("9", "9度");
        map.put("10", "自设防");
        return map;
    }


    private void getSameGridDataForPga(List<CasualtiesResult> centerResultList, String type, List<LinkedHashMap> popoluationList) {
        List<CasualtiesResult> finalResultList = new ArrayList<>();
        //四个概率水准
        Map<String, List<CasualtiesResult>> pgaMap = centerResultList.stream().collect(Collectors.groupingBy(CasualtiesResult::getCondition));
        Map<Object, List<LinkedHashMap>> linkedMap = popoluationList.stream().collect(Collectors.groupingBy(linkedHashMap -> linkedHashMap.get("extends1")));
        pgaMap.forEach((k2, v2) -> {
            Map<String, List<CasualtiesResult>> collect = v2.stream().collect(Collectors.groupingBy(CasualtiesResult::getIntensity));
            collect.forEach((k, v) -> {
                Map<String, List<CasualtiesResult>> collect1 = v.stream().collect(Collectors.groupingBy(CasualtiesResult::getExtends1));
                //不同地震烈度下13张表中同属一个房屋格网的数据
                collect1.forEach((k1, v1) -> {
                    BigDecimal totalArea = v1.stream()
                            .map(CasualtiesResult::getTotalArea)
                            .reduce(BigDecimal.ZERO, BigDecimal::add).setScale(6, RoundingMode.DOWN);
                    CasualtiesResult casualtiesResult = v1.get(0);
                    List<LinkedHashMap> linkedHashMaps = linkedMap.get(casualtiesResult.getExtends1());
                    //todo 需要真实的数据替换
                    BigDecimal m = BigDecimal.valueOf(0.2);
                    if (PlatformObjectUtils.isNotEmpty(linkedHashMaps) && linkedHashMaps.size() > 0) {
                        LinkedHashMap linkedHashMap = linkedHashMaps.get(0);
                        //格网总人口
                        BigDecimal personNum = new BigDecimal(linkedHashMap.get("tzl3").toString());
                        if (totalArea.compareTo(BigDecimal.ZERO) > 0) {
                            m = personNum.divide(totalArea, 6, RoundingMode.HALF_DOWN);
                        }
                    }
                    //获取13张表同属于一个网格的死亡和重伤人数的总和
                    BigDecimal nightDeath = v1.stream()
                            .map(CasualtiesResult::getNightDeath)
                            .reduce(BigDecimal.ZERO, BigDecimal::add).setScale(6, RoundingMode.DOWN);
                    casualtiesResult.setNightDeath(nightDeath.multiply(m));
                    casualtiesResult.setNightDeathCorrectionValue(nightDeath.multiply(m));
                    BigDecimal nightInjure = v1.stream()
                            .map(CasualtiesResult::getNightInjure)
                            .reduce(BigDecimal.ZERO, BigDecimal::add).setScale(6, RoundingMode.DOWN);
                    casualtiesResult.setNightInjure(nightInjure.multiply(m));
                    casualtiesResult.setNightInjureCorrectionValue(nightInjure.multiply(m));
                    BigDecimal dayDeath = v1.stream()
                            .map(CasualtiesResult::getDayDeath)
                            .reduce(BigDecimal.ZERO, BigDecimal::add).setScale(6, RoundingMode.DOWN);
                    casualtiesResult.setDayDeath(dayDeath.multiply(m));
                    casualtiesResult.setDayDeathCorrectionValue(dayDeath.multiply(m));
                    BigDecimal dayInjure = v1.stream()
                            .map(CasualtiesResult::getDayInjure)
                            .reduce(BigDecimal.ZERO, BigDecimal::add).setScale(6, RoundingMode.DOWN);
                    casualtiesResult.setDayInjure(dayInjure.multiply(m));
                    casualtiesResult.setDayInjureCorrectionValue(dayInjure.multiply(m));
                    casualtiesResult.setTotalArea(totalArea);
                    //casualtiesResult.setFlag(flag);
                    finalResultList.add(casualtiesResult);
                });
            });
        });
        if ("1".equals(type)) {
            casualtiesDERepository.batchSaveCasualtyResult(finalResultList);
        }
    }

    private String getPgaIntensity(ProbabilityLevel probabilityLevel, String type) {
        StringBuilder stringBuilder = new StringBuilder();
        if ("0".equals(type)) {
            try {
                stringBuilder.append("≤5".equals(probabilityLevel.getPga50year63()) ? "5" : probabilityLevel.getPga50year63()).append(",");
                stringBuilder.append("≤5".equals(probabilityLevel.getPga50year10()) ? "5" : probabilityLevel.getPga50year10()).append(",");
                stringBuilder.append("≤5".equals(probabilityLevel.getPga50year2()) ? "5" : probabilityLevel.getPga50year2()).append(",");
                stringBuilder.append("≤5".equals(probabilityLevel.getPga100year1()) ? "5" : probabilityLevel.getPga100year1()).append(",");
            }catch (Exception e){
                e.printStackTrace();
            }
        } else {
                stringBuilder.append(getIntensityByPga(probabilityLevel.getPga50year63())).append(",");
                stringBuilder.append(getIntensityByPga(probabilityLevel.getPga50year10())).append(",");
                stringBuilder.append(getIntensityByPga(probabilityLevel.getPga50year2())).append(",");
                stringBuilder.append(getIntensityByPga(probabilityLevel.getPga100year1())).append(",");
        }
        return stringBuilder.substring(0, stringBuilder.length() - 1);
    }

    private List<CasualtiesResult> handlePgaIntensity(List<ProbabilityLevel> intensityList, PCC pcc, List<DictEntityVo> dictItemByDictId
            , CalculationTasks calculationTasks, String type, List<StructureHouseUsingPercent> percentList
            , String version, String seismicInputMode) throws Exception {
        handleDistirct(pcc);
        //获取当前区县的易损性数据
        Map<String, Map<String, Map<String, BuildingVulnerability>>> ysxTable = ySXUtil.getYSX(calculationTasks.getId(), pcc.getPpName(), pcc.getCityName(), pcc.getName());
        Map<String, List<Grid13VO>> gridMap = new HashMap<>();
        List<Grid13VO> gridDataListAll = calculationTasksRepository.getLdDate(calculationTasks.getId(), seismicInputMode, "",pcc.getPpName(),pcc.getCityName(),pcc.getName(),"");
        if (PlatformObjectUtils.isNotEmpty(gridDataListAll) && gridDataListAll.size() > 0) {
            //按照格网id分组
            gridMap = gridDataListAll.stream().filter(grid13VO -> org.apache.commons.lang3.StringUtils.isNotBlank(grid13VO.getExtends1())).collect(Collectors.groupingBy(Grid13VO::getExtends1));
        }
        Map<String, ProbabilityLevel> proMap = intensityList.stream().collect(Collectors.toMap(ProbabilityLevel::getExtends1, Function.identity()));
        //type=1是烈度数据，2是pga数据
        List<CasualtiesResult> influenceResultList = new ArrayList<>();
        //处理数据获取烈度和pga的对应关系
        //for (ProbabilityLevel probabilityLevel : intensityList) {
        //<格网id,格网数据>
        gridMap.forEach((k1,v1)->{
            ProbabilityLevel probabilityLevel = proMap.get(k1);
            if(probabilityLevel!=null){
                List<Grid13VO> grid13VOS = v1;
                SettingInfluenceFliedEntity earthquakeAffected = new SettingInfluenceFliedEntity();
                earthquakeAffected.setDzIntensity(getPgaIntensity(probabilityLevel, type));
                for (int i = 1;i<5;i++){
                    String pga = "sgglsz"+i;
                    earthquakeAffected.setId(pga);
                    //根据字典值获取不同结构类型的具体数据并计算
                    if (PlatformObjectUtils.isNotEmpty(grid13VOS) && grid13VOS.size() > 0) {
                        List<CasualtiesResult> resultList  = null;
                        try {
                            resultList = getYwData(grid13VOS, ysxTable, calculationTasks, pcc, earthquakeAffected,
                                            version, "1", percentList, seismicInputMode);
                        } catch (Exception e) {
                           throw new RuntimeException(e.getMessage());
                        }

                        influenceResultList.addAll(resultList);
                    }
                }
            }
        });
        //}
        return influenceResultList;
    }

    private String getIntensityByPga(String pgaTemp) {
        String intensity = "";
        BigDecimal pga = new BigDecimal(pgaTemp);
        if (pga.compareTo(BigDecimal.valueOf(0.04))< 0 ) {
            intensity = "5";
        }else if (pga.compareTo(BigDecimal.valueOf(0.04)) >= 0 && pga.compareTo(BigDecimal.valueOf(0.09)) < 0) {
            intensity = "6";
        } else if (pga.compareTo(BigDecimal.valueOf(0.09)) >= 0 && pga.compareTo(BigDecimal.valueOf(0.19)) < 0) {
            intensity = "7";
        } else if (pga.compareTo(BigDecimal.valueOf(0.19)) >= 0 && pga.compareTo(BigDecimal.valueOf(0.38)) < 0) {
            intensity = "8";
        } else if (pga.compareTo(BigDecimal.valueOf(0.38)) >= 0 && pga.compareTo(BigDecimal.valueOf(0.75)) < 0) {
            intensity = "9";
        } else if (pga.compareTo(BigDecimal.valueOf(0.75)) >= 0) {
            intensity = "10";
        }
        return intensity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void calculationIntensity(String intensityVersion, String assessId) {
        //先删除这个评估记录之前生成的结果
        casualtiesDERepository.deleteEvaluateResult(assessId, "2");
        //list保存的是所有不重复的网格数据
        List<CasualtiesResultVO> list = new ArrayList<>();
        //根据版本查询对应的烈度iD
        List<String> idList = seismicImpactFieldRepository.getInfluencefliedId(intensityVersion);
        List<CasualtiesResultVO> voList = casualtiesDERepository.getTempEvaluateResult(idList, assessId);
        //按照格网分组
        Map<String, List<CasualtiesResultVO>> listMap = voList.stream().collect(Collectors.groupingBy(CasualtiesResultVO::getGeographyId));
        listMap.forEach((k, v) -> {
            //按照影响场烈度圈id分组 collect的value相同的格网跨越不同的烈度 也就是不同烈度中存在相同的格网数据
            Map<String, List<CasualtiesResultVO>> collect = v.stream().collect(Collectors.groupingBy(CasualtiesResultVO::getFsiId));
            if (collect.values().size() > 1) {
                //表示一个网格跨越不同的烈度圈
                List<CasualtiesResultVO> tempList = null;
                Iterator<Map.Entry<String, List<CasualtiesResultVO>>> iterator = collect.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, List<CasualtiesResultVO>> next = iterator.next();
                    List<CasualtiesResultVO> value = next.getValue();
                    if (tempList == null) {
                        tempList = value;
                    } else {
                        CasualtiesResultVO dataPbeInjuriesVo = tempList.get(0);
                        CasualtiesResultVO dataPbeInjuriesVo1 = value.get(0);
                        //当同一个格网跨越不同烈度时判断该格网的归属问题，在哪个烈度中的相交面积越大则该格网归属哪个烈度
                        if (dataPbeInjuriesVo.getArea() < dataPbeInjuriesVo1.getArea()) {
                            tempList = value;
                        }
                    }
                }
                list.addAll(tempList);
            } else {
                //表示一个网格只归属于一个烈度
                list.addAll(v);
            }
        });
        //批量保存
        casualtiesDERepository.batchSaveCasualtyResultVO(list);
        //批量删除临时表里的数据
        casualtiesDERepository.batchDelete(assessId);
        //刷新指定超图工作空间数据源数据集
        //boolean bool = hypergraphService.getWorkspaceReload("fxqh_casualties_calculation_ed");
    }

    // public void calculationIntensity1(String intensityVersion, String assessId) {
    //     //先删除这个评估记录之前生成的结果
    //     casualtiesDERepository.deleteEvaluateResult1(assessId);
    //     //list保存的是所有不重复的网格数据
    //     List<CasualtiesResultVO> list = new ArrayList<>();
    //     //根据版本查询对应的烈度iD
    //     List<String> idList = seismicImpactFieldRepository.getInfluencefliedId(intensityVersion);
    //     List<CasualtiesResultVO> voList = casualtiesDERepository.getTempEvaluateResult(idList, assessId);
    //     //按照格网分组
    //     Map<String, List<CasualtiesResultVO>> listMap = voList.stream().collect(Collectors.groupingBy(CasualtiesResultVO::getGeographyId));
    //     listMap.forEach((k, v) -> {
    //         //按照影响场烈度圈id分组 collect的value相同的格网跨越不同的烈度 也就是不同烈度中存在相同的格网数据
    //         Map<String, List<CasualtiesResultVO>> collect = v.stream().collect(Collectors.groupingBy(CasualtiesResultVO::getFsiId));
    //         if (collect.values().size() > 1) {
    //             //表示一个网格跨越不同的烈度圈
    //             List<CasualtiesResultVO> tempList = null;
    //             Iterator<Map.Entry<String, List<CasualtiesResultVO>>> iterator = collect.entrySet().iterator();
    //             while (iterator.hasNext()) {
    //                 Map.Entry<String, List<CasualtiesResultVO>> next = iterator.next();
    //                 List<CasualtiesResultVO> value = next.getValue();
    //                 if (tempList == null) {
    //                     tempList = value;
    //                 } else {
    //                     CasualtiesResultVO dataPbeInjuriesVo = tempList.get(0);
    //                     CasualtiesResultVO dataPbeInjuriesVo1 = value.get(0);
    //                     //当同一个格网跨越不同烈度时判断该格网的归属问题，在哪个烈度中的相交面积越大则该格网归属哪个烈度
    //                     if (dataPbeInjuriesVo.getArea() < dataPbeInjuriesVo1.getArea()) {
    //                         tempList = value;
    //                     }
    //                 }
    //             }
    //             list.addAll(tempList);
    //         } else {
    //             //表示一个网格只归属于一个烈度
    //             list.addAll(v);
    //         }
    //     });
    //     //批量保存
    //     casualtiesDERepository.batchSaveCasualtyResultVO(list);
    //     //批量删除临时表里的数据
    //     casualtiesDERepository.batchDelete(assessId);
    //     //刷新指定超图工作空间数据源数据集
    //     //boolean bool = hypergraphService.getWorkspaceReload("fxqh_casualties_calculation_ed");
    // }
    private List<Grid13VO> centerEvaluate1(List<DictEntityVo> dictItemByDictId, CalculationTasks calculationTasks, String version
            , List<StructureHouseUsingPercent> percentList, String seismicInputMode) throws Exception {
        List<Grid13VO> centerResultList = new ArrayList<>();
        //数据视图条件
        QueryByVersionParam queryByVersionParam = new QueryByVersionParam();
        //写入条件版本号
        queryByVersionParam.setVersionCode(calculationTasks.getHouseData());
        if ("2".equals(seismicInputMode)) {
            queryByVersionParam.setGeomType(1);
            queryByVersionParam.setInfluenceVersion(version);
        }
        queryByVersionParam.setGeom(calculationTasks.getCoordinateRange());
        for (DictEntityVo vo : dictItemByDictId) {
            queryByVersionParam.setTypeCode(vo.getDictItemCode());
            //jggwList是13张表数据其中的一张数据
            List<Grid13VO> jggwList = null;
            if ("2".equals(seismicInputMode)) {
                List<Grid13VO> jggwList1 = fxqhBuildingGridDataVersionService.queryDataByParam1(queryByVersionParam);
                //一个格网与多个地震烈度的影响场相交，取相交面积最大的一个地震烈度的影响场
                jggwList = initList(jggwList1);
            } else {
                jggwList = fxqhBuildingGridDataVersionService.queryYwData(queryByVersionParam);
            }
            centerResultList.addAll(jggwList);
        }
        return centerResultList;
    }

    private List<Grid13VO> initList(List<Grid13VO> jggwList1) {
        Map<String, Grid13VO> initMap = new HashMap<>();
        for (Grid13VO vo1 : jggwList1) {
            String key = vo1.getExtends1();
            if (initMap.containsKey(key)) {
                Grid13VO vo2 = initMap.get(key);
                if ((vo2.getArea()).compareTo(vo1.getArea()) < 0) {
                    initMap.put(key, vo1);
                }
            } else {
                initMap.put(key, vo1);
            }
        }
        return new ArrayList<>(initMap.values());
    }

    private List<CasualtiesResult> centerEvaluate(PCC pcc, List<DictEntityVo> dictItemByDictId, CalculationTasks calculationTasks
            , SettingInfluenceFliedEntity earthquakeAffected, String version, String inputMode, List<StructureHouseUsingPercent> percentList
            , String seismicInputMode,Map<String, Map<String, Map<String, BuildingVulnerability>>> ysxTable) throws Exception {
        handleDistirct(pcc);

        List<CasualtiesResult> centerResultList = new ArrayList<>();
        //影响场id
        String influencefliedId = earthquakeAffected == null?"" : earthquakeAffected.getId();
        List<Grid13VO> gridDataListAll = calculationTasksRepository.getLdDate(calculationTasks.getId(), seismicInputMode, "",pcc.getPpName(),pcc.getCityName(),pcc.getName(),influencefliedId);
        //根据省市县和版本查询13张表数据
        if (dictItemByDictId.size() > 0 && gridDataListAll.size()>0) {
            for (DictEntityVo vo : dictItemByDictId) {
                String structureType = vo.getDictItemCode();
                List<Grid13VO> jggwList = gridDataListAll.stream().filter(grid13VO -> structureType.equals(grid13VO.getDictionary())).distinct().collect(Collectors.toList());
                //根据字典值获取不同结构类型的具体数据并计算
                if (PlatformObjectUtils.isNotEmpty(jggwList) && jggwList.size() > 0) {
                    List<CasualtiesResult> resultList = getYwData(jggwList, ysxTable, calculationTasks, pcc,
                            earthquakeAffected, version, inputMode, percentList, seismicInputMode);
                    centerResultList.addAll(resultList);
                }
            }
        }
        return centerResultList;
    }

    //截取城市、区县的名称
    private void handleDistirct(PCC pcc) {
        //辽宁省-大连市->大连市
        if (org.apache.commons.lang3.StringUtils.isNotBlank(pcc.getCityName())) {
            if (pcc.getCityName().split("-").length == 2) {
                pcc.setCityName(pcc.getCityName().split("-")[1]);
            }
        }
        //辽宁省-大连市-中山区->中山区
        if (org.apache.commons.lang3.StringUtils.isNotBlank(pcc.getName())) {
            if (pcc.getName().split("-").length == 3) {
                pcc.setName(pcc.getName().split("-")[2]);
            }
        }
    }

    //获取同个房屋网格人员伤亡数据并进行批量保存
    private void getSameGridData(List<CasualtiesResult> centerResultList, String type, List<LinkedHashMap> popoluationList) {
        List<CasualtiesResult> finalResultList = new ArrayList<>();
        //按烈度分组<烈度,List<CasualtiesResult>>
        Map<String, List<CasualtiesResult>> collect = centerResultList.stream().collect(Collectors.groupingBy(CasualtiesResult::getIntensity));
        //人员按相同房屋网格id分组<相同房屋网格id,List<LinkedHashMap>>
        Map<Object, List<LinkedHashMap>> linkedMap = popoluationList.stream().filter(linkedHashMap -> PlatformObjectUtils.isNotEmpty(linkedHashMap.get("extends1"))).collect(Collectors.groupingBy(linkedHashMap -> linkedHashMap.get("extends1")));
        //不同地震烈度下13张表中同属一个房屋格网的数据
        collect.forEach((k, v) -> {
            Map<String, List<CasualtiesResult>> collect1 = v.stream().filter(casualtiesResult -> PlatformObjectUtils.isNotEmpty(casualtiesResult.getExtends1())).collect(Collectors.groupingBy(CasualtiesResult::getExtends1));
            collect1.forEach((k1, v1) -> {
                //13张表中同属于一个房屋网格的13条数据面积之和 才是这个完整网格的面积
                BigDecimal totalArea = v1.stream()
                        .map(CasualtiesResult::getTotalArea)
                        .reduce(BigDecimal.ZERO, BigDecimal::add).setScale(6, RoundingMode.DOWN);
                CasualtiesResult casualtiesResult = v1.get(0);
                List<LinkedHashMap> linkedHashMaps = linkedMap.get(casualtiesResult.getExtends1());
                BigDecimal m = BigDecimal.ZERO;
                if (PlatformObjectUtils.isNotEmpty(linkedHashMaps) && linkedHashMaps.size() > 0) {
                    LinkedHashMap linkedHashMap = linkedHashMaps.get(0);
                    //格网总人口
                    BigDecimal personNum = new BigDecimal(linkedHashMap.get("tzl3").toString());
                    if (totalArea.compareTo(BigDecimal.ZERO) > 0) {
                        m = personNum.divide(totalArea, 6, RoundingMode.HALF_DOWN);
                    }
                } else {
                    //todo 如果获取不到该网格的人口数据，就按照0处理
                    m = BigDecimal.ZERO;
                    //throw new RuntimeException("评估失败,获取不到id为" + casualtiesResult.getGeographyId() + "的人口数据");
                }
                //获取13张表同属于一个网格的死亡和重伤人数的总和
                BigDecimal nightDeath = v1.stream()
                        .map(CasualtiesResult::getNightDeath)
                        .reduce(BigDecimal.ZERO, BigDecimal::add).setScale(6, RoundingMode.DOWN);
                casualtiesResult.setNightDeath(nightDeath.multiply(m));
                casualtiesResult.setNightDeathCorrectionValue(nightDeath.multiply(m));
                BigDecimal nightInjure = v1.stream()
                        .map(CasualtiesResult::getNightInjure)
                        .reduce(BigDecimal.ZERO, BigDecimal::add).setScale(6, RoundingMode.DOWN);
                casualtiesResult.setNightInjure(nightInjure.multiply(m));
                casualtiesResult.setNightInjureCorrectionValue(nightInjure.multiply(m));
                BigDecimal dayDeath = v1.stream()
                        .map(CasualtiesResult::getDayDeath)
                        .reduce(BigDecimal.ZERO, BigDecimal::add).setScale(6, RoundingMode.DOWN);
                casualtiesResult.setDayDeath(dayDeath.multiply(m));
                casualtiesResult.setDayDeathCorrectionValue(dayDeath.multiply(m));
                BigDecimal dayInjure = v1.stream()
                        .map(CasualtiesResult::getDayInjure)
                        .reduce(BigDecimal.ZERO, BigDecimal::add).setScale(6, RoundingMode.DOWN);
                casualtiesResult.setDayInjure(dayInjure.multiply(m));
                casualtiesResult.setDayInjureCorrectionValue(dayInjure.multiply(m));
                casualtiesResult.setTotalArea(totalArea);
                //casualtiesResult.setFlag(flag);
                finalResultList.add(casualtiesResult);
            });
        });


        if ("1".equals(type)) {
            casualtiesDERepository.batchSaveCasualtyResult(finalResultList);
        } else if ("2".equals(type)) {
            //如果是2表示影响场，此时数据并不是最终结果，需要暂时保存在临时表中，等待此评估结果执行完毕后执行ajax异步回调另一个接口，目的是
            //处理格网跨不同烈度的问题，处理完成后的结果才是正式结果，正式结果执行的是type为1的业务逻辑。
            casualtiesDERepository.batchSaveCasualtyTempResult(finalResultList);
        }
    }

    //室内人员昼夜在三类结构中的的百分比
    private List<BigDecimal> getRatioByStructureCategory(String houseUsing) {
        List<BigDecimal> list = new ArrayList();
        if ("1".equals(houseUsing)) {
            list = Arrays.asList(BigDecimal.valueOf(0.925), BigDecimal.valueOf(0.225));
        } else if ("2".equals(houseUsing)) {
            list = Arrays.asList(BigDecimal.valueOf(0.035), BigDecimal.valueOf(0.825));
        } else if ("3".equals(houseUsing)) {
            list = Arrays.asList(BigDecimal.valueOf(0.55), BigDecimal.valueOf(0.025));
        }
        return list;
    }

    private Map<Integer, String> intensityMap() {
        Map<Integer, String> map = new HashMap<>();
        //Ⅵ度(6)度	Ⅵ	6
        map.put(5, "V");
        map.put(6, "Ⅵ");
        map.put(7, "Ⅶ");
        map.put(8, "Ⅷ");
        map.put(9, "Ⅸ");
        map.put(10, "Ⅹ");
        return map;
    }

    private List<String> getIntensityList(Grid13VO obj) {
        List<String> intensityList = new ArrayList<>();
        if (obj.getSfIntensity() > 0) {
            intensityList.add("未设防");
        }
        if (obj.getSfIntensity6() > 0) {
            intensityList.add("6度");
        }
        if (obj.getSfIntensity7() > 0) {
            intensityList.add("7度");
        }
        if (obj.getSfIntensity8() > 0) {
            intensityList.add("8度");
        }
        if (obj.getSfIntensity9() > 0) {
            intensityList.add("9度");
        }
        //实际数据中有的数据，现设防程度占比全是0时，按未设防值100%计算。
        if (intensityList.size() == 0) {
            intensityList.add("未设防");
        }
        return intensityList;
    }

    private Map<String, BigDecimal> getIntensitArea(Grid13VO obj) {
        Map<String, BigDecimal> map = new HashMap<>();
        //实际数据中有的数据，现设防程度占比全是0时，按未设防值100%计算。
        if ((obj.getSfIntensity() == null || obj.getSfIntensity() == 0) && (obj.getSfIntensity6() == null || obj.getSfIntensity6() == 0) &&
                (obj.getSfIntensity7() == null || obj.getSfIntensity7() == 0) && (obj.getSfIntensity8() == null || obj.getSfIntensity8() == 0) &&
                (obj.getSfIntensity9() == null || obj.getSfIntensity9() == 0)) {
            map.put("未设防", BigDecimal.valueOf(100));
        } else {
            map.put("未设防", obj.getSfIntensity() == null || obj.getSfIntensity() == 0 ? BigDecimal.ZERO : BigDecimal.valueOf(obj.getSfIntensity()));
            map.put("6度", (obj.getSfIntensity6() == null || obj.getSfIntensity6() == 0) ? BigDecimal.ZERO : BigDecimal.valueOf(obj.getSfIntensity6()));
            map.put("7度", obj.getSfIntensity7() == null || obj.getSfIntensity7() == 0 ? BigDecimal.ZERO : BigDecimal.valueOf(obj.getSfIntensity7()));
            map.put("8度", obj.getSfIntensity8() == null || obj.getSfIntensity8() == 0 ? BigDecimal.ZERO : BigDecimal.valueOf(obj.getSfIntensity8()));
            map.put("9度", obj.getSfIntensity9() == null || obj.getSfIntensity9() == 0 ? BigDecimal.ZERO : BigDecimal.valueOf(obj.getSfIntensity9()));
        }

        return map;
    }

    private Table buildStructureTable() {
        Table<String, String, String> ysxTable = HashBasedTable.create();
        ysxTable.put("城镇砌体结构", "城镇砌体结构", "砌体结构-砖混结构");
        ysxTable.put("城镇钢混结构", "19", "剪力墙结构");
        ysxTable.put("城镇钢结构", "城镇钢结构", "钢结构");
        ysxTable.put("城镇木结构", "城镇木结构", "木结构");
        ysxTable.put("城镇其他结构", "城镇其他结构", "其他");
        ysxTable.put("农村砌体结构", "农村砌体结构", "砌体结构-砖混结构");
        ysxTable.put("农村土木（石木）结构", "农村土木（石木）结构", "土木结构");
        ysxTable.put("农村底部框架结构", "农村底部框架结构", "砌体结构-砖混结构");
        ysxTable.put("农村木（竹）结构", "农村木（竹）结构", "木结构");
        ysxTable.put("农村混杂结构", "农村混杂结构", "其他");
        ysxTable.put("农村钢混结构", "农村钢混结构", "钢筋混凝土结构-框架结构");
        ysxTable.put("农村钢结构", "农村钢结构", "钢结构");
        ysxTable.put("农村其他结构", "农村其他结构", "其他");
        ysxTable.put("城镇钢混结构", "8", "钢筋混凝土结构-框架结构");
        ysxTable.put("城镇钢混结构", "18", "钢筋混凝土结构-框架-剪力墙结构");
        return ysxTable;
    }

    private List<CasualtiesResult> getYwData(List<Grid13VO> jggwList, Map<String, Map<String, Map<String, BuildingVulnerability>>> ysxTable, CalculationTasks calculationTasks
            , PCC pcc, SettingInfluenceFliedEntity earthquakeAffected, String version, String inputMode
            , List<StructureHouseUsingPercent> percentList, String seismicInputMode) throws Exception {
        List<CasualtiesResult> calculationTotalList = new ArrayList<>();
        //一个obj就是一个网格
        for (Grid13VO obj : jggwList) {
            //总面积当前坐标总面积
            Double totalArea = obj.getTotalArea();
            //住宅房屋面积（第Ⅰ类）
            BigDecimal residence = (obj.getResidence() == 0.0 ? BigDecimal.ZERO : (BigDecimal.valueOf(obj.getResidence()).divide(BigDecimal.valueOf(100), 6, RoundingMode.HALF_DOWN)));
            //办公房屋面积（第Ⅱ类）
            BigDecimal office = (obj.getOffice() == 0.0 ? BigDecimal.ZERO : (BigDecimal.valueOf(obj.getOffice()).divide(BigDecimal.valueOf(100), 6, RoundingMode.HALF_DOWN)));
            //商业房屋面积（第Ⅲ类）
            BigDecimal business = (obj.getBusiness() == 0.0 ? BigDecimal.ZERO : (BigDecimal.valueOf(obj.getBusiness()).divide(BigDecimal.valueOf(100), 6, RoundingMode.HALF_DOWN)));
            //医疗教育面积（第Ⅲ类）
            BigDecimal medic = (obj.getMedic() == 0.0 ? BigDecimal.ZERO : (BigDecimal.valueOf(obj.getMedic()).divide(BigDecimal.valueOf(100), 6, RoundingMode.HALF_DOWN)));
            //其他房屋面积（第Ⅲ类）
            BigDecimal other = (obj.getOther() == 0.0 ? BigDecimal.ZERO : (BigDecimal.valueOf(obj.getOther()).divide(BigDecimal.valueOf(100), 6, RoundingMode.HALF_DOWN)));
            if (residence.compareTo(BigDecimal.ZERO) == 0 && office.compareTo(BigDecimal.ZERO) == 0 && business.compareTo(BigDecimal.ZERO) == 0
                    && medic.compareTo(BigDecimal.ZERO) == 0 && other.compareTo(BigDecimal.ZERO) == 0) {
                //格网面积有但是各个房屋用途均为0需要使用数据库中存储的各房屋用途备用比例
                Map<String, List<StructureHouseUsingPercent>> collect = percentList.stream().collect(Collectors.groupingBy(StructureHouseUsingPercent::getStructure));
                StructureHouseUsingPercent structureHouseUsingPercent = collect.get(obj.getStructureType()).get(0);
                residence = structureHouseUsingPercent.getResidence();
                office = structureHouseUsingPercent.getOffice();
                business = structureHouseUsingPercent.getBusiness();
                medic = structureHouseUsingPercent.getMedic();
                other = structureHouseUsingPercent.getOther();
            }
            BigDecimal residenceArea = residence.multiply(BigDecimal.valueOf(totalArea));
            BigDecimal officeArea = office.multiply(BigDecimal.valueOf(totalArea));
            BigDecimal businessArea = business.multiply(BigDecimal.valueOf(totalArea));
            BigDecimal medicArea = medic.multiply(BigDecimal.valueOf(totalArea));
            BigDecimal otherArea = other.multiply(BigDecimal.valueOf(totalArea));

            // //map <建筑结构,<设防烈度,建筑物易损性的结合>>
            // Map<String, Map<String, Map<String, BuildingVulnerability>>> map = ysxTable.rowMap();
            String mapKey = "";
            //获取对应易损性结构类型
            if (!"城镇钢混结构".equals(obj.getStructureType())) {
                mapKey = (String) buildStructureTable().get(obj.getStructureType(), obj.getStructureType());
            } else {
                //城镇钢混结构需要根据建筑的楼层确定易损性结构类型
                if ((obj.getF1() + obj.getF2F3() + obj.getF4F6() + obj.getF7F10() + obj.getF11F16() + obj.getF17F30() + obj.getF31()) == 0) {
                    //实际数据中有的数据层数占比全是0，无层数百分比，结构类型对应时，城镇钢混结构对应到钢筋混凝土结构-框架结构
                    mapKey = (String) buildStructureTable().get(obj.getStructureType(), "8");
                } else {
                    if (obj.getF31() > 0 || obj.getF17F30() > 0) {
                        mapKey = (String) buildStructureTable().get(obj.getStructureType(), "19");
                    } else if (obj.getF7F10() > 0 || obj.getF11F16() > 0) {
                        mapKey = (String) buildStructureTable().get(obj.getStructureType(), "18");
                    } else {
                        mapKey = (String) buildStructureTable().get(obj.getStructureType(), "8");
                    }
                }
                if ("剪力墙结构".equals(mapKey)) {
                    mapKey = "钢筋混凝土结构-" + mapKey;
                }
            }
            //组建13张表数据中烈度和对应的烈度面积占比结构
            Map<String, BigDecimal> intensitAreaMap = getIntensitArea(obj);
            //<设防烈度,建筑物易损性的结合>
            Map<String, Map<String, BuildingVulnerability>> sfIntensityMap = ysxTable.get(mapKey);
            //每种结构所具备的设防烈度
            List<String> intensityList = getIntensityList(obj);
            List<CasualtiesResult> calculationList = new ArrayList<>();
            //设置地震烈度
//            List<Integer> dzIntensityList = getDzIntensityList(earthquakeAffected, inputMode);
            String id = "";
            if(PlatformObjectUtils.isNotEmpty(earthquakeAffected)){
                id = earthquakeAffected.getId();
            }
            List<Integer> dzIntensityList = getDzIntensityList(earthquakeAffected, inputMode,id);
            if (intensityList.size() > 0) {
                //6-10表示真实的地震烈度
               // int num = 1;
                //i是5-10度
                for (Integer i : dzIntensityList) {
                    CasualtiesResult casualtiesResult = new CasualtiesResult();
                    //每个地震烈度下不同建筑物类型白天死亡、重伤人数；夜晚死亡、重伤人数
                    BigDecimal nightTotalDeathNum = BigDecimal.ZERO;
                    BigDecimal nightTotalInjureNum = BigDecimal.ZERO;
                    BigDecimal dayTotalDeathNum = BigDecimal.ZERO;
                    BigDecimal dayTotalInjureNum = BigDecimal.ZERO;
                    if (sfIntensityMap != null && sfIntensityMap.size() > 0) {
                        //每种结构所具备的设防烈度（未设防-9度）
                        for (String intensity : intensityList) {
                            //易损性数据下设防烈度对应的数据
                            Map<String, BuildingVulnerability> vulnerabilityList = sfIntensityMap.get(intensity);
                            if(PlatformObjectUtils.isEmpty(vulnerabilityList) || vulnerabilityList.size()==0){
                                throw new RuntimeException("计算未完成，无法获取"+mapKey+"下设防情况为"+intensity+"的易损性数据");
                            }
                            BuildingVulnerability buildingVulnerability = vulnerabilityList.get(i + "");
                            if(PlatformObjectUtils.isEmpty(buildingVulnerability)){
                                throw new RuntimeException("计算未完成，无法获取"+mapKey+"下设防情况为"+intensity+"烈度为"+i+"度的易损性数据");
                            }
                            //不同设防烈度房屋面积占比
                            BigDecimal ratio = intensitAreaMap.get(intensity).divide(BigDecimal.valueOf(100), 4, RoundingMode.HALF_DOWN);
                            //三类房屋用途在不同设防烈度下的面积
                            BigDecimal residenceRatioArea = residenceArea.multiply(ratio);
                            BigDecimal officeRatioArea = officeArea.multiply(ratio);
                            BigDecimal businessRatioArea = businessArea.multiply(ratio);
                            BigDecimal medicRatioArea = medicArea.multiply(ratio);
                            BigDecimal otherRatioArea = otherArea.multiply(ratio);
                            //不同结构类型中的三类结构在不同设防烈度下、地震烈度为6-10度下的人员死亡和重伤人数
                            Map<String, BigDecimal> resultMap = getCasualtiesValue(residenceRatioArea, officeRatioArea, businessRatioArea, medicRatioArea, otherRatioArea, vulnerabilityList, i);
                            //resultMap是不同结构类型的房屋网格在每个地震烈度下的各个设防烈度下的人员死亡和人员重伤
                            BigDecimal nd = resultMap.get("nd");
                            //夜间人员死亡
                            nightTotalDeathNum = nightTotalDeathNum.add(nd);
                            BigDecimal ni = resultMap.get("ni");
                            //夜间人员重伤
                            nightTotalInjureNum = nightTotalInjureNum.add(ni);
                            BigDecimal dd = resultMap.get("dd");
                            //白天人员死亡
                            dayTotalDeathNum = dayTotalDeathNum.add(dd);
                            BigDecimal di = resultMap.get("di");
                            //白天人员重伤
                            dayTotalInjureNum = dayTotalInjureNum.add(di);
                        }
                    }
                    casualtiesResult.setId(UUIDGenerator.getUUID());
                    casualtiesResult.setAssessId(calculationTasks.getId());
                    casualtiesResult.setAssessCode(calculationTasks.getAssessCode());
                    casualtiesResult.setProvinceName(pcc.getPpName());
                    casualtiesResult.setCityName(pcc.getCityName());
                    casualtiesResult.setCountyName(pcc.getName());
                    casualtiesResult.setGeographyId(obj.getExtends1());
                    casualtiesResult.setDayDeath(dayTotalDeathNum);
                    casualtiesResult.setDayDeathCorrectionValue(dayTotalDeathNum);
                    casualtiesResult.setNightDeath(nightTotalDeathNum);
                    casualtiesResult.setNightDeathCorrectionValue(nightTotalDeathNum);
                    casualtiesResult.setDayInjure(dayTotalInjureNum);
                    casualtiesResult.setDayInjureCorrectionValue(dayTotalInjureNum);
                    casualtiesResult.setNightInjure(nightTotalInjureNum);
                    casualtiesResult.setNightInjureCorrectionValue(nightTotalInjureNum);
                    //如果是地震影响场condition存的是影响场iD，如果是烈度，condition存的是烈度，如果是四个概率水准，则存的是四个概率水准对应的数据
                    if (earthquakeAffected != null) {
                        String fsiId = earthquakeAffected.getId();
//                        if ("1".equals(inputMode)) {
//                            fsiId = fsiId.substring(0, fsiId.length() - 1);
//                            fsiId = fsiId + "" + num;
//                        }
                        casualtiesResult.setCondition(org.apache.commons.lang3.StringUtils.isNotBlank(fsiId) ? fsiId : version);
                        casualtiesResult.setIntensity(intensityMap().get(i));
                    } else {
                        casualtiesResult.setCondition("");
                        casualtiesResult.setIntensity(intensityMap().get(i));
                    }
                    casualtiesResult.setStructure(obj.getStructureType());
                    casualtiesResult.setGeom(obj.getGeom());
                    casualtiesResult.setTotalArea(obj.getTotalArea() == null || obj.getTotalArea() == 0 ? BigDecimal.ZERO : BigDecimal.valueOf(obj.getTotalArea()));
                    casualtiesResult.setCreateUser(PlatformSessionContext.getUserID());
                    casualtiesResult.setCreateTime(new Date());
                    casualtiesResult.setDelFlag("0");
                    casualtiesResult.setVersion(version);
                    casualtiesResult.setExtends1(obj.getExtends1());
                    casualtiesResult.setFlag(seismicInputMode);
                    calculationList.add(casualtiesResult);
                }
            }
            calculationTotalList.addAll(calculationList);
        }
        return calculationTotalList;
    }

    //手动构建地震烈度
    private List<Integer> getDzIntensityList(SettingInfluenceFliedEntity earthquakeAffected, String inputMode,String pga) {
        List<Integer> dzIntensityList = new ArrayList<>();
        if (earthquakeAffected != null) {
            //1表示选择了四个标准概率
            if ("1".equals(inputMode)) {
                try{
                    String intensity = earthquakeAffected.getDzIntensity();
                    String[] split = intensity.split(",");
                    if(PlatformObjectUtils.isNotEmpty(pga)){
                        if("sgglsz1".equals(pga)){
                            dzIntensityList.add(Integer.valueOf(split[0]));
                        }else if("sgglsz2".equals(pga)){
                            dzIntensityList.add(Integer.valueOf(split[1]));
                        }else if("sgglsz3".equals(pga)){
                            dzIntensityList.add(Integer.valueOf(split[2]));
                        }else if("sgglsz4".equals(pga)){
                            dzIntensityList.add(Integer.valueOf(split[3]));
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }

//                for (String insten : split) {
//                    dzIntensityList.add(Integer.valueOf(insten));
//                }
                return dzIntensityList;
            }
            dzIntensityList.add(Integer.valueOf(earthquakeAffected.getDzIntensity()));
            return dzIntensityList;
        }
        return Arrays.asList(6, 7, 8, 9, 10);
    }

    private Map<String, BigDecimal> getCasualtiesValue(BigDecimal residenceArea, Map<String, BuildingVulnerability> vulnerabilityList, int intensity, String houseUsing, BigDecimal density) {
        BigDecimal ndeathNum = BigDecimal.ZERO;
        BigDecimal ninjureNum = BigDecimal.ZERO;
        BigDecimal ddeathNum = BigDecimal.ZERO;
        BigDecimal dinjureNum = BigDecimal.ZERO;
        //不同结构类型中的住宅房屋（第一类结构）在不同设防烈度、地震烈度为6-10度下的人员死亡和重伤人数
        Table table1 = mathCasualties(residenceArea, vulnerabilityList, houseUsing, intensity, density);
        ndeathNum = ndeathNum.add((BigDecimal) table1.get("night", "death"));
        ninjureNum = ninjureNum.add((BigDecimal) table1.get("night", "injure"));
        ddeathNum = ddeathNum.add((BigDecimal) table1.get("day", "death"));
        dinjureNum = dinjureNum.add((BigDecimal) table1.get("day", "injure"));
        Map<String, BigDecimal> map = new HashMap<>();
        map.put("nd", ndeathNum);
        map.put("ni", ninjureNum);
        map.put("dd", ddeathNum);
        map.put("di", dinjureNum);
        return map;
    }


    private Map<String, BigDecimal> getCasualtiesValue(BigDecimal residenceArea, BigDecimal officeArea, BigDecimal businessArea, BigDecimal medicArea, BigDecimal otherArea, Map<String, BuildingVulnerability> vulnerabilityList, int intensity) {
        BigDecimal ndeathNum = BigDecimal.ZERO;
        BigDecimal ninjureNum = BigDecimal.ZERO;
        BigDecimal ddeathNum = BigDecimal.ZERO;
        BigDecimal dinjureNum = BigDecimal.ZERO;
        //不同结构类型中的住宅房屋（第一类结构）在不同设防烈度、地震烈度为6-10度下的人员死亡和重伤人数
        Table table1 = mathCasualties(residenceArea, vulnerabilityList, "1", intensity, null);
        if (table1 != null && table1.size() > 0) {
            ndeathNum = ndeathNum.add((BigDecimal) table1.get("night", "death"));
            ninjureNum = ninjureNum.add((BigDecimal) table1.get("night", "injure"));
            ddeathNum = ddeathNum.add((BigDecimal) table1.get("day", "death"));
            dinjureNum = dinjureNum.add((BigDecimal) table1.get("day", "injure"));
        }
        //不同结构类型中的办公房屋（第2类结构）在不同设防烈度、地震烈度为6-10度下的人员死亡和重伤人数
        Table table2 = mathCasualties(officeArea, vulnerabilityList, "2", intensity, null);
        if (table2 != null && table2.size() > 0) {
            ndeathNum = ndeathNum.add((BigDecimal) table2.get("night", "death"));
            ninjureNum = ninjureNum.add((BigDecimal) table2.get("night", "injure"));
            ddeathNum = ddeathNum.add((BigDecimal) table2.get("day", "death"));
            dinjureNum = dinjureNum.add((BigDecimal) table2.get("day", "injure"));
        }
        //不同结构类型中的商业房屋（第3类结构）在不同设防烈度、地震烈度为6-10度下的人员死亡和重伤人数
        Table table3 = mathCasualties(businessArea, vulnerabilityList, "3", intensity, null);
        if (table3 != null && table3.size() > 0) {
            ndeathNum = ndeathNum.add((BigDecimal) table3.get("night", "death"));
            ninjureNum = ninjureNum.add((BigDecimal) table3.get("night", "injure"));
            ddeathNum = ddeathNum.add((BigDecimal) table3.get("day", "death"));
            dinjureNum = dinjureNum.add((BigDecimal) table3.get("day", "injure"));
        }
        //不同结构类型中的医疗教育（第3类结构）在不同设防烈度、地震烈度为6-10度下的人员死亡和重伤人数
        Table table4 = mathCasualties(medicArea, vulnerabilityList, "3", intensity, null);
        if (table4 != null && table4.size() > 0) {
            ndeathNum = ndeathNum.add((BigDecimal) table4.get("night", "death"));
            ninjureNum = ninjureNum.add((BigDecimal) table4.get("night", "injure"));
            ddeathNum = ddeathNum.add((BigDecimal) table4.get("day", "death"));
            dinjureNum = dinjureNum.add((BigDecimal) table4.get("day", "injure"));
        }
        //不同结构类型中中的其他房屋（第3类结构）在不同设防烈度、地震烈度为6-10度下的人员死亡和重伤人数
        Table table5 = mathCasualties(otherArea, vulnerabilityList, "3", intensity, null);
        if (table5 != null && table5.size() > 0) {
            ndeathNum = ndeathNum.add((BigDecimal) table5.get("night", "death"));
            ninjureNum = ninjureNum.add((BigDecimal) table5.get("night", "injure"));
            ddeathNum = ddeathNum.add((BigDecimal) table5.get("day", "death"));
            dinjureNum = dinjureNum.add((BigDecimal) table5.get("day", "injure"));
        }
        Map<String, BigDecimal> map = new HashMap<>();
        map.put("nd", ndeathNum);
        map.put("ni", ninjureNum);
        map.put("dd", ddeathNum);
        map.put("di", dinjureNum);
        return map;
    }


    //计算不同结构类型房屋在地震烈度为6-10度下的的死亡和重伤人数 intensity是地震烈度
    private Table mathCasualties(BigDecimal area, Map<String, BuildingVulnerability> vulnerabilityList, String houseUsing, int intensity, BigDecimal density) {
        BuildingVulnerability buildingVulnerability = vulnerabilityList.get(intensity + "");
        //倒塌程度下的地震烈度为N的易损性数据
        BigDecimal dintensity = buildingVulnerability.getDestroy();
        //严重破坏程度下的地震烈度为N的易损性数据
        BigDecimal sintensity = buildingVulnerability.getSerious();
        //中等破坏程度下的地震烈度为N的易损性数据
        BigDecimal mintensity = buildingVulnerability.getMid();
        //轻微破坏破坏程度下的地震烈度为N的易损性数据
        BigDecimal ssintensity = buildingVulnerability.getSlight();
        return publicOperate(houseUsing, area, dintensity, sintensity, mintensity, ssintensity, density);
    }

    private Table publicOperate(String houseUsing, BigDecimal area, BigDecimal dintensity, BigDecimal sintensity, BigDecimal mintensity, BigDecimal ssintensity, BigDecimal density) {
        Table table = HashBasedTable.create();
        //rd1倒塌房屋内的死亡率
        BigDecimal rd1 = BigDecimal.ONE.divide(BigDecimal.valueOf(60), 6, RoundingMode.HALF_DOWN);
        //rh1倒塌房屋内的重伤率
        BigDecimal rh1 = BigDecimal.ONE.divide(BigDecimal.valueOf(15), 6, RoundingMode.HALF_DOWN);

        //rd2， rh2—分别是严重破坏房屋内的死亡率和重伤率
        BigDecimal rd2 = BigDecimal.ONE.divide(BigDecimal.valueOf(1000), 6, RoundingMode.HALF_DOWN);
        BigDecimal rh2 = BigDecimal.ONE.divide(BigDecimal.valueOf(200), 6, RoundingMode.HALF_DOWN);

        //rd3， rh3—分别是中等破坏房屋内的死亡率和重伤率
        BigDecimal rd3 = BigDecimal.ONE.divide(BigDecimal.valueOf(100000), 6, RoundingMode.HALF_DOWN);
        BigDecimal rh3 = BigDecimal.ONE.divide(BigDecimal.valueOf(10000), 6, RoundingMode.HALF_DOWN);

        //rh4 是轻微破坏房屋内的重伤率
        BigDecimal rh4 = BigDecimal.ONE.divide(BigDecimal.valueOf(100000), 6, RoundingMode.HALF_DOWN);
        //计算城镇钢混结构下第Ⅰ类结构在设防烈度为未设防、地震烈度为6度、白天和夜晚下的下的死亡人数和重伤人数
        //C是地震时第n类结构人员在室内的百分比
        List<BigDecimal> cList = getRatioByStructureCategory(houseUsing);
        for (int i = 0; i < 2; i++) {
            BigDecimal prefixResult = cList.get(i);
            if (density != null) {
                prefixResult = prefixResult.multiply(density);
            }
            //(A1rd1 +A2rd2 +A3rd3)
            //rd1-rd3分别是倒塌房屋内的死亡率、严重破坏房屋内的死亡率、中等破坏房屋内的死亡率
            //A1rd1  A1倒塌房屋的面积  倒塌房屋的面积  =房屋面积*倒塌比
            BigDecimal A1rd1 = area.multiply(dintensity == null ? BigDecimal.ZERO : dintensity.divide(BigDecimal.valueOf(100), 6, RoundingMode.HALF_DOWN)).multiply(rd1);
            //A2rd2  A2严重破坏房屋的面积  严重破坏房屋的面积 =房屋面积*严重破坏比
            BigDecimal A2rd2 = area.multiply(sintensity == null ? BigDecimal.ZERO : sintensity.divide(BigDecimal.valueOf(100), 6, RoundingMode.HALF_DOWN)).multiply(rd2);
            //A3rd3  A3中等破坏房屋的面积  中等破坏房屋的面积  =房屋面积*中等破坏比
            BigDecimal A3rd3 = area.multiply(mintensity == null ? BigDecimal.ZERO : mintensity.divide(BigDecimal.valueOf(100), 6, RoundingMode.HALF_DOWN)).multiply(rd3);

            //死亡人数
            BigDecimal deathNum = prefixResult.multiply(A1rd1.add(A2rd2).add(A3rd3));
            //重伤人数
            BigDecimal A1rh1 = area.multiply(dintensity == null ? BigDecimal.ZERO : dintensity.divide(BigDecimal.valueOf(100), 6, RoundingMode.HALF_DOWN)).multiply(rh1);
            BigDecimal A2rh2 = area.multiply(sintensity == null ? BigDecimal.ZERO : sintensity.divide(BigDecimal.valueOf(100), 6, RoundingMode.HALF_DOWN)).multiply(rh2);
            BigDecimal A3rh3 = area.multiply(mintensity == null ? BigDecimal.ZERO : mintensity.divide(BigDecimal.valueOf(100), 6, RoundingMode.HALF_DOWN)).multiply(rh3);
            BigDecimal A4rh4 = area.multiply(ssintensity == null ? BigDecimal.ZERO : ssintensity.divide(BigDecimal.valueOf(100), 6, RoundingMode.HALF_DOWN)).multiply(rh4);
            BigDecimal injureNum = prefixResult.multiply(A1rh1.add(A2rh2).add(A3rh3).add(A4rh4));
            if (i == 0) {
                //夜间
                table.put("night", "death", deathNum);
                table.put("night", "injure", injureNum);
            } else {
                //白天
                table.put("day", "death", deathNum);
                table.put("day", "injure", injureNum);
            }
        }
        return table;
    }

//     //根据省市县获取本省市县下的所有易损性
//     private HashMap<String, Map<String, Map<String, YSXEntity>>> getYSX(String pid, String cid, String id) {
//
//         String[] cName = cid.split("-");
//         List<YSXEntity> list = ysxRepository.getYSX(pid, cName[1], id);
//         //结构类型
//         HashMap<String, Map<String, Map<String, YSXEntity>>> structureType = new HashMap<>();
//         //创建数据结构
//         for (int j = 0; j < 13; j++) {
//             Map<String, Map<String, YSXEntity>> fortify = new HashMap<>();
//             for (int i = 0; i < 7; i++) {
//                 Map<String, YSXEntity> intensity = new HashMap<>();
//                 if (i == 0) {
//                     fortify.put("未设防", intensity);
//                 }
//                 if (i == 1) {
//                     fortify.put("6度", intensity);
//                 }
//                 if (i == 2) {
//                     fortify.put("7度", intensity);
//                 }
//                 if (i == 3) {
//                     fortify.put("8度", intensity);
//                 }
//                 if (i == 4) {
//                     fortify.put("9度", intensity);
//                 }
//                 if (i == 5) {
//                     fortify.put("自设防", intensity);
//                 }
//                 if (i == 6) {
//                     fortify.put("其他", intensity);
//                 }
//             }
//             if (j == 0) {
//                 structureType.put("czghjggw", fortify);
//             }
//             if (j == 1) {
//                 structureType.put("czmjggw", fortify);
//             }
//             if (j == 2) {
//                 structureType.put("czqtjglxgw", fortify);
//             }
//             if (j == 3) {
//                 structureType.put("czqtjggw", fortify);
//             }
//             if (j == 4) {
//                 structureType.put("ncdbkjkzqqtjggw", fortify);
//             }
//             if (j == 5) {
//                 structureType.put("ncghjggw", fortify);
//             }
//             if (j == 6) {
//                 structureType.put("ncgjggw", fortify);
//             }
//             if (j == 7) {
//                 structureType.put("nchzjggw", fortify);
//             }
//             if (j == 8) {
//                 structureType.put("ncmzjggw", fortify);
//             }
//             if (j == 9) {
//                 structureType.put("ncqtjglxgw", fortify);
//             }
//             if (j == 10) {
//                 structureType.put("ncqtjggw", fortify);
//             }
//             if (j == 11) {
//                 structureType.put("nctmsmjggw", fortify);
//             }
//             if (j == 12) {
//                 structureType.put("czgjggw", fortify);
//             }
//         }
//         //写入数据
//         for (YSXEntity ysxEntity : list) {
//             //根据结构类型
//             switch (ysxEntity.getStructure_type()) {
//                 //城镇钢混结构房屋网格
//                 case "钢筋混凝土结构-框架结构":
//                     //根据结构类型分
//                     Map<String, YSXEntity> czghjggw = structureType.get("czghjggw").get(ysxEntity.getFortify());
//                     getDamageDegreeMap(ysxEntity, czghjggw);
//                     Map<String, YSXEntity> ncgjggw = structureType.get("ncgjggw").get(ysxEntity.getFortify());
//                     getDamageDegreeMap(ysxEntity, ncgjggw);
//                     break;
// //                case "钢筋混凝土结构-框架-剪力墙结构":
// //                    Map<String, YSX> czghjggw2 = structureType.get("czghjggw2").get(ysx.getFortify());
// //                    getDamageDegreeMap(ysx, czghjggw2);
// //                    break;
// //                case "剪力墙结构":
// //                    //根据结构类型分
// //                    Map<String, YSX> czghjggw3 = structureType.get("czghjggw3").get(ysx.getFortify());
// //                    getDamageDegreeMap(ysx, czghjggw3);
// //                    break;
//                 //城镇木结构房屋格网
//                 case "木结构":
//                     Map<String, YSXEntity> czmjggw = structureType.get("czmjggw").get(ysxEntity.getFortify());
//                     getDamageDegreeMap(ysxEntity, czmjggw);
//                     Map<String, YSXEntity> ncmzjggw = structureType.get("ncmzjggw").get(ysxEntity.getFortify());
//                     getDamageDegreeMap(ysxEntity, ncmzjggw);
//                     break;
//                 //城镇其他结构房屋格网
//                 case "其他":
//                     Map<String, YSXEntity> czqtjglxgw = structureType.get("czqtjglxgw").get(ysxEntity.getFortify());
//                     getDamageDegreeMap(ysxEntity, czqtjglxgw);
//                     Map<String, YSXEntity> nchzjggw = structureType.get("nchzjggw").get(ysxEntity.getFortify());
//                     getDamageDegreeMap(ysxEntity, nchzjggw);
//                     Map<String, YSXEntity> ncqtjglxgw = structureType.get("ncqtjglxgw").get(ysxEntity.getFortify());
//                     getDamageDegreeMap(ysxEntity, ncqtjglxgw);
//                     break;
//                 //城镇砌体结构房屋格网
//                 case "砌体结构-砖混结构":
//                     Map<String, YSXEntity> czqtjggw = structureType.get("czqtjggw").get(ysxEntity.getFortify());
//                     getDamageDegreeMap(ysxEntity, czqtjggw);
//                     Map<String, YSXEntity> ncdbkjkzqqtjggw = structureType.get("ncdbkjkzqqtjggw").get(ysxEntity.getFortify());
//                     getDamageDegreeMap(ysxEntity, ncdbkjkzqqtjggw);
//                     Map<String, YSXEntity> ncqtjggw = structureType.get("ncqtjggw").get(ysxEntity.getFortify());
//                     getDamageDegreeMap(ysxEntity, ncqtjggw);
//                     break;
//                 //农村土木（石木）结构房屋格网
//                 case "土木结构":
//                     Map<String, YSXEntity> nctmsmjggw = structureType.get("nctmsmjggw").get(ysxEntity.getFortify());
//                     getDamageDegreeMap(ysxEntity, nctmsmjggw);
//                     break;
//                 //城镇钢结构房屋格网
//                 case "钢结构":
//                     Map<String, YSXEntity> czgjggw = structureType.get("czgjggw").get(ysxEntity.getFortify());
//                     getDamageDegreeMap(ysxEntity, czgjggw);
//                     break;
//                 default:
//                     break;
//             }
//         }
//         return structureType;
//     }

    //获取破坏状态map
    private void getDamageDegreeMap(YSXEntity ysxEntity, Map<String, YSXEntity> map) {
        //破坏状态
        switch (ysxEntity.getDamage_degree()) {
            case "基本完好":
                map.put("基本完好", ysxEntity);
                break;
            case "轻微破坏":
                map.put("轻微破坏", ysxEntity);
                break;
            case "中等破坏":
                map.put("中等破坏", ysxEntity);
                break;
            case "严重破坏":
                map.put("严重破坏", ysxEntity);
                break;
            case "倒塌":
                map.put("倒塌", ysxEntity);
                break;
        }
    }

    private String buildGeographyId(int index) {
        return index < 100 ? (index < 10 ? "dl00" + index : "dl0" + index) : "dl" + index;
    }


    //导入计算数据
//    @Override
//    public String reportImport(InputStream inputStream, String type, String id, String code) {
//        Workbook workbook = null;
//        try {
//            workbook = WorkbookFactory.create(inputStream);
//
//            Map<String, Object> map = getList(workbook, type, id, code);
//            Object o = map.get("message");
//            if (o != null) {
//                return String.valueOf(o);
//            } else {
//                List<CasualtiesDECalculation> list = (List<CasualtiesDECalculation>) map.get("list");
//                casualtiesDERepository.batchCalculation(list);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return "成功";
//    }


    @Override
    public String reportImport(InputStream inputStream, String id) throws Exception {
        CasualtiesDE byId = this.getById(id);
        //选择的房屋基础数据
        //0为单体1为网格 根据iD查询空间数据
        String houseDataFlag = byId.getHouseDataFlag();
        //获取评估区域中的省市区县
        List<PCC> list = byId.getList();
        if (PlatformObjectUtils.isEmpty(list)) {
            throw new RuntimeException("导入失败,目前只支持按省市区县导入");
        }
        String seismicInputMode = byId.getSeismicInputMode();
//        if (!"0".equals(seismicInputMode)) {
//            throw new RuntimeException("导入失败,目前只支持按烈度导入");
//        }
        if (!seismicInputMode.contains("0")) {
            throw new RuntimeException("导入失败,目前只支持按烈度导入");
        }
        Workbook workbook = WorkbookFactory.create(inputStream);
        Map<String, Object> map = getList(workbook, byId);
        if (map.get("message") != null) {
            //表示校验失败返回失败信息
            return map.get("message").toString();
        }
        //批量保存
        List<CasualtiesResult> finalList = (List<CasualtiesResult>) map.get("list");
        casualtiesDERepository.batchSaveCasualtyResult(finalList);
        return "导入成功";
    }

    private Map<String, Object> getList(Workbook workbook, CasualtiesDE casualtiesDE) throws Exception {
        Map<String, Object> map = new HashMap<>();
        List<CasualtiesResult> finalList = new ArrayList<>();

        List<PCC> list = casualtiesDE.getList();
        List<String> areaList = list.stream().map(pcc -> pcc.getPpName() + "-" + pcc.getCityName() + "-" + pcc.getName()).collect(Collectors.toList());
        //查询烈度信息
        List<String> intensityList = dictItemService.getDictItemNameByDictId("3985cdf6c6964638b75521b6cf3b8648");
        if (workbook != null) {
            //循环除了第一行的所有行
            /** 得到第一个sheet */
            Sheet sheet = workbook.getSheetAt(0);
            /** 得到Excel的行数 */
            int totalRows = sheet.getPhysicalNumberOfRows();
            HSSFDataFormatter hSSFDataFormatter = new HSSFDataFormatter();
            List<CasualtiesResult> resultList = new ArrayList<>();
            /** 循环Excel的行 从第4行开始*/
            for (int r = 3; r < totalRows; r++) {
                Row row = sheet.getRow(r);
                if (row == null) {
                    continue;
                }
                CasualtiesResult obj = new CasualtiesResult();
                //数据校验
                Map<String, Object> check = check(row, areaList, intensityList, r + 1);
                //如果没有message
                if (check.get("message") == null || "".equals(check.get("message"))) {
                    //省
                    obj.setProvinceName(hSSFDataFormatter.formatCellValue(row.getCell(0)));
                    //市
                    obj.setCityName(hSSFDataFormatter.formatCellValue(row.getCell(1)));
                    //县
                    obj.setCountyName(hSSFDataFormatter.formatCellValue(row.getCell(2)));
                    //建筑物公里网格ID（建筑物单体ID）
                    obj.setGeographyId(hSSFDataFormatter.formatCellValue(row.getCell(3)));
                    //烈度
                    obj.setIntensity( hSSFDataFormatter.formatCellValue(row.getCell(4)));
                    //人员伤亡
                    String casualties = hSSFDataFormatter.formatCellValue(row.getCell(5));
                    //时间段
                    String time = hSSFDataFormatter.formatCellValue(row.getCell(6));
                    obj.setFlag("0");
                    if ("白天".equals(time)) {
                        if ("重伤".equals(casualties)) {
                            obj.setDayInjure(new BigDecimal(hSSFDataFormatter.formatCellValue(row.getCell(7))));
                            obj.setDayInjureCorrectionValue(new BigDecimal(hSSFDataFormatter.formatCellValue(row.getCell(8))));
                        } else if ("死亡".equals(casualties)) {
                            obj.setDayDeath(new BigDecimal(hSSFDataFormatter.formatCellValue(row.getCell(7))));
                            obj.setDayDeathCorrectionValue(new BigDecimal(hSSFDataFormatter.formatCellValue(row.getCell(8))));
                        }
                    } else if ("夜间".equals(time)) {
                        if ("重伤".equals(casualties)) {
                            obj.setNightInjure(new BigDecimal(hSSFDataFormatter.formatCellValue(row.getCell(7))));
                            obj.setNightInjureCorrectionValue(new BigDecimal(hSSFDataFormatter.formatCellValue(row.getCell(8))));
                        } else if ("死亡".equals(casualties)) {
                            obj.setNightDeath(new BigDecimal(hSSFDataFormatter.formatCellValue(row.getCell(7))));
                            obj.setNightDeathCorrectionValue(new BigDecimal(hSSFDataFormatter.formatCellValue(row.getCell(8))));
                        }
                    }
                } else {
                    return check;
                }
                //评估记录id
                obj.setAssessId(casualtiesDE.getId());
                //评估记录code
                obj.setAssessCode(casualtiesDE.getAssessCode());
                //主键id
                obj.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                //创建人
                obj.setCreateUser(PlatformSessionContext.getUserID());
                //创建时间
                obj.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
                obj.setDelFlag("0");
                //todo 设置空间数据
                obj.setCondition("");
                obj.setVersion("");
                resultList.add(obj);
            }
            if (resultList.size() > 0) {
                Map<String, List<CasualtiesResult>> collect = resultList.stream().collect(Collectors.groupingBy(CasualtiesResult::getGeographyId));
                collect.forEach((k, v) -> {
                    CasualtiesResult result = v.get(0);
                    for (CasualtiesResult temp : v) {
                        if (PlatformObjectUtils.isNotEmpty(temp.getDayDeath())) {
                            result.setDayDeath(temp.getDayDeath());
                        }
                        if (PlatformObjectUtils.isNotEmpty(temp.getDayInjure())) {
                            result.setDayInjure(temp.getDayInjure());
                        }
                        if (PlatformObjectUtils.isNotEmpty(temp.getNightDeath())) {
                            result.setNightDeath(temp.getNightDeath());
                        }
                        if (PlatformObjectUtils.isNotEmpty(temp.getNightInjure())) {
                            result.setNightInjure(temp.getNightInjure());
                        }
                        if (PlatformObjectUtils.isNotEmpty(temp.getDayDeathCorrectionValue())) {
                            result.setDayDeathCorrectionValue(temp.getDayDeathCorrectionValue());
                        }
                        if (PlatformObjectUtils.isNotEmpty(temp.getDayInjureCorrectionValue())) {
                            result.setDayInjureCorrectionValue(temp.getDayInjureCorrectionValue());
                        }
                        if (PlatformObjectUtils.isNotEmpty(temp.getNightDeathCorrectionValue())) {
                            result.setNightDeathCorrectionValue(temp.getNightDeathCorrectionValue());
                        }
                        if (PlatformObjectUtils.isNotEmpty(temp.getNightInjureCorrectionValue())) {
                            result.setNightInjureCorrectionValue(temp.getNightInjureCorrectionValue());
                        }
                    }
                    finalList.add(result);
                });
            }
        }
        map.put("list", finalList);
        return map;
    }

    //根据条件查询计算值
    @Override
    public Map<String, Object> queryCalculation(Integer curPage, Integer pageSize, String seismicInputMode, String id, String condition, String casualties, String time) {
        return casualtiesDERepository.queryCalculation(curPage, pageSize, id, condition, casualties, time, seismicInputMode);
    }

    //导出
    @Override
    public void exportData(HttpServletResponse response, CasualtiesDECalculationParam param) {
        //条件(地震烈度 或 四个概率水准)
        if ("0".equals(param.getSeismicInputMode())) {
            //隐藏经纬度范围字段
            ArrayList<String> list1 = new ArrayList<>();
            list1.add("condition");
            ExcelUtil.hideColumn(QhSynthesisExportVO.class, list1, true);
        }
        if ("1".equals(param.getSeismicInputMode())) {
            //隐藏经纬度范围字段
            ArrayList<String> list1 = new ArrayList<>();
            list1.add("intensity");
            ExcelUtil.hideColumn(QhSynthesisExportVO.class, list1, true);
            ExcelUtil.setExcelAnnotationValue(QhSynthesisExportVO.class, "condition",
                    "name", "四个概率");
        }
        if ("2".equals(param.getSeismicInputMode())) {
            CalculationTasks byId = calculationTasksRepository.findById(param.getId());
            param.setCondition(byId.getInfluenceFieldVersion());
            //隐藏经纬度范围字段
            ArrayList<String> list1 = new ArrayList<>();
            list1.add("intensity");
            ExcelUtil.hideColumn(QhSynthesisExportVO.class, list1, true);
            ArrayList<String> list2 = new ArrayList<>();
            list2.add("condition");
            ExcelUtil.hideColumn(QhSynthesisExportVO.class, list2, true);
        }
        List<ExportVO> listData = casualtiesDERepository.getListPCC(param);
        try {
            EasyPoiExcelUtil.exportExcel(listData, "人员伤亡", "人员伤亡", ExportVO.class, "人员伤亡确定评估计算.xlsx", response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public void updateCorrectionValue(String id, BigDecimal correctionValue, String time, String casualties) {
        correctionValue = correctionValue.setScale(0, RoundingMode.DOWN);
        casualtiesDERepository.updateCorrectionValue(id, correctionValue, time, casualties);
    }

//    //获取list
//    private Map<String, Object> getList(Workbook workbook, String type, String id, String code) throws UnsupportedEncodingException {
//        String userID = PlatformSessionContext.getUserID();
//        Map<String, Object> map = new HashMap<>();
//        List<CasualtiesDECalculation> list = new ArrayList<>();
//        Boolean mark = true;
//        if (Integer.parseInt(type) > 2) {
//            mark = false;
//        }
//        if (workbook != null) {
//            //循环除了第一行的所有行
//            /** 得到第一个sheet */
//            Sheet sheet = workbook.getSheetAt(0);
//            /** 得到Excel的行数 */
//            int totalRows = sheet.getPhysicalNumberOfRows();
//            HSSFDataFormatter hSSFDataFormatter = new HSSFDataFormatter();
//            /** 循环Excel的行 从第4行开始*/
//            for (int r = 3; r < totalRows; r++) {
//                Row row = sheet.getRow(r);
//                if (row == null) {
//                    continue;
//                }
//                CasualtiesDECalculation obj = new CasualtiesDECalculation();
//                if (mark) {
//                    //按照省市县输入时校验
//                    Map<String, Object> check = check(row, type);
//                    //如果没有message
//                    if (check.get("message") == null) {
//                        //省
//                        obj.setProvinceName(hSSFDataFormatter.formatCellValue(row.getCell(0)));
//                        //市
//                        obj.setCityName(hSSFDataFormatter.formatCellValue(row.getCell(1)));
//                        //县
//                        obj.setCountyName(hSSFDataFormatter.formatCellValue(row.getCell(2)));
//                        //建筑物公里网格ID（建筑物单体ID）
//                        obj.setGeographyId(hSSFDataFormatter.formatCellValue(row.getCell(3)));
//                        //条件(地震烈度 或 四个概率水准)
//                        if (type.equals("1")) {
//                            obj.setCondition(dictService.getKeyByDictCodeAndValue("ld", hSSFDataFormatter.formatCellValue(row.getCell(4))));
//                        } else {
//                            obj.setCondition(dictService.getKeyByDictCodeAndValue("sgglsz", hSSFDataFormatter.formatCellValue(row.getCell(4))));
//                        }
//
//                        //人员伤亡
//                        obj.setCasualties(dictService.getKeyByDictCodeAndValue("rysw", hSSFDataFormatter.formatCellValue(row.getCell(5))));
//                        //时间段
//                        obj.setTime(dictService.getKeyByDictCodeAndValue("sjd", hSSFDataFormatter.formatCellValue(row.getCell(6))));
//                        //计算值
//                        obj.setCalculatedValue(new BigDecimal(hSSFDataFormatter.formatCellValue(row.getCell(7))));
//                        //经验评估与修正值
//                        obj.setCorrectionValue(new BigDecimal(hSSFDataFormatter.formatCellValue(row.getCell(7))));
//                    } else {
//                        return check;
//                    }
//                } else {
//                    //按照坐标范围输入时校验
//                    Map<String, Object> check = check2(row, type);
//                    //如果没有message
//                    if (check.get("message") == null) {
//                        //经纬度坐标范围
//                        obj.setCoordinateRange(hSSFDataFormatter.formatCellValue(row.getCell(0)));
//                        //建筑物公里网格ID（建筑物单体ID）
//                        obj.setGeographyId(hSSFDataFormatter.formatCellValue(row.getCell(1)));
//                        //条件(地震烈度 或 四个概率水准)
//                        if (type.equals("2")) {
//                            obj.setCondition(dictService.getKeyByDictCodeAndValue("ld", hSSFDataFormatter.formatCellValue(row.getCell(2))));
//                        } else {
//                            obj.setCondition(dictService.getKeyByDictCodeAndValue("sgglsz", hSSFDataFormatter.formatCellValue(row.getCell(2))));
//                        }
//                        //人员伤亡
//                        obj.setCasualties(dictService.getKeyByDictCodeAndValue("rysw", hSSFDataFormatter.formatCellValue(row.getCell(3))));
//                        //时间段
//                        obj.setTime(dictService.getKeyByDictCodeAndValue("sjd", hSSFDataFormatter.formatCellValue(row.getCell(4))));
//                        //计算值
//                        obj.setCalculatedValue(new BigDecimal(hSSFDataFormatter.formatCellValue(row.getCell(5))));
//                        //经验评估与修正值
//                        obj.setCorrectionValue(new BigDecimal(hSSFDataFormatter.formatCellValue(row.getCell(5))));
//                    } else {
//                        return check;
//                    }
//                }
//                //评估记录id
//                obj.setAssessId(id);
//                //评估记录code
//                obj.setAssessCode(code);
//                //主键id
//                obj.setId(UUID.randomUUID().toString().replaceAll("-", ""));
//                //创建人
//                obj.setCreateUser(userID);
//                //创建时间
//                obj.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
//                list.add(obj);
//            }
//        }
//        map.put("list", list);
//        return map;
//    }

    //数据校验省市县
    private Map<String, Object> check(Row row, List<String> areaList, List<String> intensityList, int index) throws UnsupportedEncodingException {
        HashMap<String, Object> map = new HashMap<>();
        HSSFDataFormatter hSSFDataFormatter = new HSSFDataFormatter();
        StringBuilder stringBuilder = new StringBuilder("第" + index + "行");
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(0)))) {
            stringBuilder.append("省不能为空,");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(1)))) {
            stringBuilder.append("市不能为空,");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(2)))) {
            stringBuilder.append("县不能为空,");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(3)))) {
            stringBuilder.append("建筑物公里网格ID（建筑物单体ID）不能为空,");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(4)))) {
            stringBuilder.append("烈度不能为空,");
        } else {
            String stringCellValue = row.getCell(4).getStringCellValue();
            if (!intensityList.contains(stringCellValue)) {
                stringBuilder.append("烈度输入错误,");
            }
        }
//        if (type.equals("1")) {
//            if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(4)))) {
//                map.put("message", "烈度不能为空");
//            }
//        } else {
//            if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(4)))) {
//                map.put("message", "四个概率水准不能为空");
//            }
//        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(6)))) {
            stringBuilder.append("人员伤亡不能为空,");
        } else {
            String stringCellValue = row.getCell(6).getStringCellValue();
            if (!"重伤".equals(stringCellValue) &&  !"死亡".equals(stringCellValue)) {
                stringBuilder.append("人员伤亡输入错误,");
            }
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(7)))) {
            stringBuilder.append("时间段不能为空,");
        } else {
            String stringCellValue = row.getCell(7).getStringCellValue();
            if (!"白天".equals(stringCellValue) && !"夜间".equals(stringCellValue)) {
                stringBuilder.append("时间段输入错误,");
            }
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(8)))) {
            stringBuilder.append("计算值不能为空,");
        } else {
            if (!StringUtils.isNumber(row.getCell(8).getStringCellValue())) {
                stringBuilder.append("计算值必须是数字,");
            }
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(8)))) {
            stringBuilder.append("经验评估与修正值不能为空,");
        } else {
            if (!StringUtils.isNumber(hSSFDataFormatter.formatCellValue(row.getCell(8)))) {
                stringBuilder.append("经验评估与修正值必须是数字,");
            }
        }
        String province = hSSFDataFormatter.formatCellValue(row.getCell(0));
        String city = hSSFDataFormatter.formatCellValue(row.getCell(1));
        String county = hSSFDataFormatter.formatCellValue(row.getCell(2));
        if (org.apache.commons.lang3.StringUtils.isNotBlank(province) &&
                org.apache.commons.lang3.StringUtils.isNotBlank(city) &&
                org.apache.commons.lang3.StringUtils.isNotBlank(county) &&
                !areaList.contains(province + "-" + city + "-" + county)) {
            stringBuilder.append(province).append("-").append(city).append("-").append(county).append("不在评估记录所选的省市县中,");
        }
        String msg = "";
        if (!("第" + index + "行").contentEquals(stringBuilder)) {
            msg = stringBuilder.substring(0, stringBuilder.length() - 1);
        }
        map.put("message", msg);
        return map;
    }

    //范围校验
    private Map<String, Object> check2(Row row, String type) throws UnsupportedEncodingException {
        HashMap<String, Object> map = new HashMap<>();
        HSSFDataFormatter hSSFDataFormatter = new HSSFDataFormatter();
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(0)))) {
            map.put("message", "坐标范围不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(1)))) {
            map.put("message", "建筑物公里网格ID（建筑物单体ID）不能为空");
        }
        if (type.equals("1")) {
            if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(2)))) {
                map.put("message", "烈度不能为空");
            }
        } else {
            if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(2)))) {
                map.put("message", "四个概率水准不能为空");
            }
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(3)))) {
            map.put("message", "人员伤亡不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(4)))) {
            map.put("message", "时间段不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(5)))) {
            map.put("message", "计算值不能为空");
        }
        return map;
    }

    /****
     * 从哪里开始计数 比如startValue=2，则会从003,004,005等
     * @param startValue
     * @return
     */
    public String getNext(String startValue) {
        Integer i = Integer.valueOf(startValue);
        String format = String.format("%04d", i + 1);
        return format;
    }

    /**
     * 确认评估风险区划-区划
     *
     * @param entity
     * @return
     */
    @Override
    public List<FxqhAssessEdQhResult> doZoning(FxqhAssessEdQh entity) throws UnsupportedEncodingException, BizException {
        List<FxqhAssessEdQhResult> resultList = new ArrayList<>();
        Map<String, String> areaIdCodeMap = (Map<String, String>) JSON.parse((String) redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "areaIdCodeMap"));
        String divisionNames = entity.getDivisionNames();
        String assessCodes = entity.getAssessCodes();
        String condition = entity.getCondition();
        for (String divisionName : divisionNames.split(",")) {
            String[] split = divisionName.split("-");
            List<Map<String, Object>> list = casualtiesDERepository.getSumByDivisionAndAssessCodes(split[0], split[1], split[2],
                    assessCodes, condition, entity.getSeismicInputMode());
            BigDecimal calculatedValue = BigDecimal.ZERO;
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> map = list.get(i);
                if (i == 0 && ((Long) map.get("count")) > 1) {
                    throw new RuntimeException("所选评估记录中有重复区县，请重新选择！");
                }
                calculatedValue = calculatedValue.add(BigDecimal.valueOf((Double) map.get("sum")));
            }
            String divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(split[0], "UTF-8"),
                    URLEncoder.encode(split[1], "UTF-8"), URLEncoder.encode(split[2], "UTF-8"));
            String code = null;
            if (areaIdCodeMap==null||areaIdCodeMap.size()<1) {
                code = sysAreaService.getDivisionCodeById(divisionIds.split("_")[2]);
            }else {
                code = areaIdCodeMap.get(divisionIds.split("_")[2]);
            }
            String geom = jcsjRestManager.getGeomByCode(code,"3");
            if (geom == null) {
                throw new RuntimeException("未获取到" + split[0] + split[1] + split[2] + "的空间数据！");
            }

            FxqhAssessEdQhResult result = new FxqhAssessEdQhResult();
            result.setProvince(split[0]);
            result.setCity(split[1]);
            result.setCounty(split[2]);
            result.setCalculatedValue(calculatedValue);
            result.setGeom(geom);
            result.setEstimateObj("2");
            resultList.add(result);
        }
        return resultList;
    }

    @Override
    public List<FxqhAssessEdQhResult> doZoning(CalculationTasks task) throws UnsupportedEncodingException, BizException {
        List<FxqhAssessEdQhResult> resultList = new ArrayList<>();
        Map<String, String> areaIdCodeMap = (Map<String, String>) JSON.parse((String) redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "areaIdCodeMap"));
        List<PCC> pccList = null;
//        if (task.getRadio2().equals("0")) {
        pccList = task.getList();
//        } else {
//            pccList = pccRepository.queryToponym(task.getId());
//        }
        for (PCC pcc : pccList) {
            String divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(pcc.getPpName(), "UTF-8"),
                    URLEncoder.encode(pcc.getCityName(), "UTF-8"), URLEncoder.encode(pcc.getName(), "UTF-8"));
            String code = null;
            if (areaIdCodeMap==null||areaIdCodeMap.size()<1) {
                code = sysAreaService.getDivisionCodeById(divisionIds.split("_")[2]);
            }else {
                code = areaIdCodeMap.get(divisionIds.split("_")[2]);
            }
            String geom = jcsjRestManager.getGeomByCode(code,"3");
            if (geom == null) {
                // throw new RuntimeException("未获取到" + pcc.getPpName() + pcc.getCityName() + pcc.getName() + "的空间数据！");
                continue;
            }
            String[] conditionArr = new String[]{};
            // 0、烈度；1、4个概率水准；2、地震影响场
            for (String seiMode : task.getSeismicInputMode().split(",")) {
                if (seiMode.equals("0")) {
                    conditionArr = new String[]{"Ⅵ", "Ⅶ", "Ⅷ", "Ⅸ", "Ⅹ"};
                } else if (seiMode.equals("1")) {
                    conditionArr = new String[]{"sgglsz1", "sgglsz2", "sgglsz3", "sgglsz4"};
                } else {
                    conditionArr = new String[]{task.getInfluenceFieldVersion()};
                }
                for (String condition : conditionArr) {
                    List<Map<String, Object>> list = casualtiesDERepository.getSumByDivisionAndAssessCodes(pcc.getPpName(), pcc.getCityName(), pcc.getName(),
                            task.getId(), condition, seiMode);
                    BigDecimal calculatedValue = BigDecimal.ZERO;
                    for (int i = 0; i < list.size(); i++) {
                        Map<String, Object> map = list.get(i);
                        calculatedValue = calculatedValue.add(BigDecimal.valueOf((Double) map.get("sum")));
                    }

                    FxqhAssessEdQhResult result = new FxqhAssessEdQhResult();
                    result.setProvince(pcc.getPpName());
                    result.setCity(pcc.getCityName());
                    result.setCounty(pcc.getName());
                    result.setCalculatedValue(calculatedValue);
                    result.setGeom(geom);
                    result.setId(UUIDGenerator.getUUID());
                    result.setTaskId(task.getId());
                    result.setEstimateObj("1");
                    result.setHouseDataFlag(task.getHouseDataFlag());
                    //"Ⅵ", "Ⅶ", "Ⅷ", "Ⅸ", "Ⅹ"
                    switch (condition) {
                        case "Ⅵ":
                            condition = "ld1";
                            break;
                        case "Ⅶ":
                            condition = "ld2";
                            break;
                        case "Ⅷ":
                            condition = "ld3";
                            break;
                        case "Ⅸ":
                            condition = "ld4";
                            break;
                        case "Ⅹ":
                            condition = "ld5";
                            break;
                    }
                    result.setCondition(condition);
                    result.setSeismicInputMode(ResistEarthquakesDEServiceImpl.getSeismicInputModeByCondition(condition));
                    resultList.add(result);
                }
            }
        }
        return resultList;
    }

    @Override
    public JSONObject versionPage(SysDataVersionPageParam param) throws BizException {
        param.setTypeCode("rkglwgsj");
        return jcsjRestManager.populationVersionPage(param);
    }

    @Override
    public List<Statistics> statistics(String seismicInputMode, String taskId, String condition, String casualties, String time) throws Exception{
        List<Statistics> proList = new ArrayList<>();
        //获取评估任务关联的省市区县
        List<PCC> pccs = pccRepository.queryToponym(taskId);
//        Map<String, PCC> pccMap = pccs.stream().collect(Collectors.toMap(PCC::getName, Function.identity()));
        if(PlatformObjectUtils.isEmpty(pccs) || pccs.size() == 0){
            throw new RuntimeException("任务没有关联任何评估区域");
        }
        List<String> provinceList = pccs.stream().map(PCC::getPpName).distinct().collect(Collectors.toList());
        for (String province : provinceList) {
            List<String> cityList = pccs.stream().filter(pcc -> province.equals(pcc.getPpName())).map(PCC::getCityName).distinct().collect(Collectors.toList());
            //根据省获取确定评估人员伤亡数据
            List<CasualtiesCalculationVO> resultList = casualtiesDERepository.getCasualtiesResult(taskId, province, condition, casualties, time, seismicInputMode);
            //存在多个市 需要展示省
            if (cityList.size() > 1) {
                BigDecimal provinceTotal = resultList.stream()
                        .map(CasualtiesCalculationVO::getCorrectionValue) // 提取每个RiskAnalysisDeductDetail的Score字段
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                Statistics proStatistics = buildEntityData(province, provinceTotal, time, casualties, seismicInputMode, condition);
                List<Statistics> cityChildren = new ArrayList<>();
                for (String city : cityList) {
                    //根据市获取确定评估人员伤亡数据
                    List<Statistics> countyChildren = new ArrayList<>();
                    BigDecimal cityTotal = resultList.stream().filter(pcc -> city.equals(pcc.getCityName()))
                            .map(CasualtiesCalculationVO::getCorrectionValue) // 提取每个RiskAnalysisDeductDetail的Score字段
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    Statistics cityStatistics = buildEntityData(city, cityTotal, time, casualties, seismicInputMode, condition);
                    List<String> countyList = pccs.stream().filter(pcc -> city.equals(pcc.getCityName())).map(PCC::getName).distinct().collect(Collectors.toList());
                    for (String county : countyList) {
                        //根据区县获取确定评估人员伤亡数据
                        BigDecimal countyTotal = resultList.stream().filter(casualtiesCalculationVO -> county.equals(casualtiesCalculationVO.getCountyName()))
                                .map(CasualtiesCalculationVO::getCorrectionValue) // 提取每个RiskAnalysisDeductDetail的Score字段
                                .reduce(BigDecimal.ZERO, BigDecimal::add);
                        Statistics countyStatistics = buildEntityData(county, countyTotal, time, casualties, seismicInputMode, condition);
                        countyChildren.add(countyStatistics);
                    }
                    cityStatistics.setChildren(countyChildren);
                    cityChildren.add(cityStatistics);
                }
                proStatistics.setChildren(cityChildren);
                proList.add(proStatistics);
            } else {
                //不需要展示省
                List<String> countyList = pccs.stream().filter(pcc -> cityList.get(0).equals(pcc.getCityName())).map(PCC::getName).distinct().collect(Collectors.toList());
                if (countyList.size() > 1) {
                    //多个县需要显示市
                    BigDecimal cityTotal = resultList.stream().filter(pcc -> cityList.get(0).equals(pcc.getCityName()))
                            .map(CasualtiesCalculationVO::getCorrectionValue) // 提取每个RiskAnalysisDeductDetail的Score字段
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    Statistics cityStatistics = buildEntityData(cityList.get(0), cityTotal, time, casualties, seismicInputMode, condition);
                    List<Statistics> countyChildren = new ArrayList<>();
                    for (String county : countyList) {
                        //根据区县获取确定评估人员伤亡数据
                        BigDecimal countyTotal = resultList.stream().filter(casualtiesCalculationVO -> county.equals(casualtiesCalculationVO.getCountyName()))
                                .map(CasualtiesCalculationVO::getCorrectionValue) // 提取每个RiskAnalysisDeductDetail的Score字段
                                .reduce(BigDecimal.ZERO, BigDecimal::add);
                        Statistics countyStatistics = buildEntityData(county, countyTotal, time, casualties, seismicInputMode, condition);
                        countyChildren.add(countyStatistics);
                    }
                    cityStatistics.setChildren(countyChildren);
                    proList.add(cityStatistics);
                } else {
                    //只需要显示区县
                    BigDecimal countyTotal = resultList.stream().filter(casualtiesCalculationVO -> countyList.get(0).equals(casualtiesCalculationVO.getCountyName()))
                            .map(CasualtiesCalculationVO::getCorrectionValue) // 提取每个RiskAnalysisDeductDetail的Score字段
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    Statistics countyStatistics = buildEntityData(countyList.get(0), countyTotal, time, casualties, seismicInputMode, condition);
                    proList.add(countyStatistics);
                }

            }
        }
        return proList;
    }
    private Statistics buildEntityData(String districtName,BigDecimal total,String time,String casualties,String seismicInputMode,String  condition){
        Statistics statistics = new Statistics();
        statistics.setId(UUIDGenerator.getUUID()).setDistrictName(districtName).setValue(total).setTime("sjd1".equals(time)?"白天":"夜间")
                .setCasualties("rysw1".equals(casualties)?"重伤":"死亡").setCondition(getDictItemVal(seismicInputMode,condition));
        return statistics;
    }
    private String getDictItemVal(String seismicInputMode,String condition){
        if ("0".equals(seismicInputMode)) {
            //烈度 condition就是烈度 ld1-ld5  casualties
            if (org.apache.commons.lang3.StringUtils.isNotBlank(condition)) {
                if ("ld1".equals(condition)) {
                    return "Ⅵ";
                } else if ("ld2".equals(condition)) {
                    return "Ⅶ";
                } else if ("ld3".equals(condition)) {
                    return "Ⅷ";
                } else if ("ld4".equals(condition)) {
                    return "Ⅸ";
                } else if ("ld5".equals(condition)) {
                    return "Ⅹ";
                }
            }
        } else if ("1".equals(seismicInputMode)) {
            //四个概率水准
            if (org.apache.commons.lang3.StringUtils.isNotBlank(condition)) {
                if ("sgglsz1".equals(condition)) {
                    return "50年内超越概率63%";
                } else if ("sgglsz2".equals(condition)) {
                    return "50年内超越概率10%";
                } else if ("sgglsz3".equals(condition)) {
                    return "50年内超越概率2%";
                } else if ("sgglsz4".equals(condition)) {
                    return "100年内超越概率1%";
                }
            }
        } else if ("2".equals(seismicInputMode)) {
            //影响场
            return "";
        }
        return "";
    }
}
